Thursday, March 30, 2017

PyGTK - Introduction

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available.
PyQt is a Python port of QT library. Our PyQt tutorial can be found here. Similarly, wxPython toolkit is Python binding for wxWidgets, another popular cross-platform GUI library. Our wxPython tutorial is available here.

PyGTK - Environment

PyGTK for Microsoft Windows

The installation of PyGTK for Microsoft Windows involves the following steps −
  • Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution)
  • Step 2 − Download and install GTK+ runtime.

PyGTK - Hello World

Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code.
import gtk
The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window.
class PyApp(gtk.Window):

PyGTK - Important Classes

The PyGTK module contains various widgets. gtk.Object class acts as the base class for most of the widgets as well as for some non-widget classes. The toplevel window for desktop applications using PyGTK is provided by gtk.Window class. The following table lists the important widgets and their functions −

PyGTK - Window Class

An object of the gtk.Window class provides a widget that users commonly think of as a Wwindow. This widget is a container hence, it can hold one child widget. It provides a displayable area decorated with title bar and resizing controls.
gtk.Window class has the following constructor −

PyGTK - Button Class

The gtk.Button widget is usually displayed as a pushbutton with a text label. It is generally used to attach a callback function or method that is called when the button is clicked.
The gtk.Button class has the following constructor −
gtk.Button(label = None, stock = None, use_underline = True)
Wherein,

PyGTK - Label Class

A Label widget is useful to display non-editable text. Label is used by many other widgets internally. For example, Button has a label to show text on the face. Similarly, MenuItem objects have a label. A label is a windowless object, so it cannot receive events directly.
Label class has a simple constructor −

PyGTK - Entry Class

Entry widget is a single-line text entry widget. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible.
Entry field can be converted in password mode using set_visibility() method of this class. Entered text is substituted by character chosen by invisible_char() method, default being '*'.
The Entry class has the following constructor −

PyGTK - Signal Handling

Unlike a console mode application, which is executed in a sequential manner, a GUI-based application is event driven. The gtk.main() function starts an infinite loop. Events occurring on the GUI are transferred to appropriate callback functions.

PyGTK - Event Handling

In addition to the signal mechanism, window system events can also be connected to callback functions. Window resizing, key press, scroll event etc. are some of common window system events. These events are reported to application's main loop. From there, they are passed along via signals to the callback functions.
Some of the system events are listed below −

PyGTK - Containers

PyGTK library provides different container classes to control the placement of widgets inside a window. The easiest way is to use a fixed container class and place a widget inside it by specifying its absolute coordinates measured in pixels.
Let us now follow these steps −

PyGTK - Box Class

The gtk.Box class is an abstract class defining the functionality of a container in which widgets are placed in a rectangular area. gtk.HBox and gtk.VBox widgets are derived from it.
Child widgets in gtk.Hbox are arranged horizontally in the same row. On the other hand, child widgets of gtk.VBox are arranged vertically in the same column.

PyGTK - ButtonBox Class

The ButtonBox class in gtk API serves as a base class for containers to hold multiple buttons either horizontally or vertically. Two subclasses HButtonBox and VButtonBox are derived from the ButtonBox class, which itself is a subclass of gtk.Box class.

PyGTK - Alignment Class

This widget proves useful in controlling alignment and size of its child widgets. It has four properties called xalign, yalign, xscale and yscale. The scale properties specify how much of free space will be used by the child widgets. The align properties areused to place the child widget within available area.

PyGTK - EventBox Class

Some widgets in PyGTK tool kit do not have their own window. Such windowless widgets cannot receive event signals. Such widgets, for example a label, if put inside an eventbox can receive signals.
EventBox is an invisible container that provides window to windowless widgets. It has a simple constructor without any argument −
gtk.EventBox()

PyGTK - Layout Class

The gtk.Layout is a container widget similar to gtk.Fixed. Widgets are placed in Layout widget by specifying absolute coordinates. However, the Layout differs from fixed widget in the following ways −
  • The layout widget can have infinite width and height. The maximum value of width and height is limited by the size of unsigned integer.

PyGTK - ComboBox Class

ComboBox is a powerful and popular widget in any GUI toolkit. It provides a dropdown list of items from which a user can choose. The gtk.ComboBox widget implements the CellLayout interface and provides a number of methods to manage the display of items.

PyGTK - ToggleButton Class

ToggleButton widget is a gtk.Button with two states — a pressed or active (or on) state and a normal or inactive (or off) state. Every time the button is pressed, the state alternates. The state of the ToggleButton can also be changed programmatically by set_active() method. To switch the state of the button, the toggled() method is also available.

PyGTK - CheckButton Class

A CheckButton widget is nothing but a ToggleButton styled as a checkbox and a label. It inherits all properties and methods from the ToggleButton class. Unlike ToggleButton where the caption is on the button's face, a CheckButton displays a small square which is checkable and has a label to its right.
Constructor, methods, and signals associated with gtk.CheckButton are exactly the same as gtk.ToggleButton.

PyGTK - RadioButton Class

A single RadioButton widget offers functionality similar to CheckButton. However, when more than one radio button is present in the same container, then a mutually exclusive choice is available for the user to choose from one of the available options. If every radio button in the container belongs to the same group, then as one is selected, others are automatically deselected.

PyGTK - MenuBar,Menu and MenuItem

A horizontal bar just below the title bar of a toplevel gtk.Window is reserved to display series of menus. It is an object of gtk.MenuBar class in PyGTK API.
An object of the gtk.Menu class is added to the menu bar. It is also used to create context menu and popup menu. Each menu may contain one or more gtk.MenuItem widgets. Some of them can be a submenu.and have cascaded MenuItem buttons.

PyGTK - Toolbar Class

Toolbar class is inherited from the gtk.Container class. It holds and manages a set of buttons and other widgets. One or more horizontal strips of buttons are normally seen just below the menu bar in a top level window. The Toolbar can also be put in a detachable window called HandleBox. By default, the buttons in the gtk.Toolbar widget are laid horizontally. Vertical toolbar can be set up by setting the orientation property

PyGTK - Adjustment Class

Some widgets in PyGTK toolkit are such that their properties can be adjusted over a specified range by the user by using a mouse or a keyboard. A widget like Viewport is used to display some adjustable portion of a large data, for example, a multiline text in TextView control.

PyGTK - Range Class

This class acts as a base class for widgets which let the user to adjust the value of a numeric parameter between the lower and upper bounds. Scale widgets (gtk.Hscale and gtk.Vscale) and scrollbar widgets (gtk.HScrollbar and gtk.VScrollbar) derive functionality from the Range class. These Range widgets work in conjunction with the Adjustment object.

PyGTK - Scale Class

This class acts as an abstract base class for HScale and VScale widgets. These widgets work as a slider control and select a numeric value.
The following methods of this abstract class are implemented by the HScale class and the VScale class −

PyGTK - Scrollbar Class

This class is an abstract base class for gtk.Hscrollbar and gtk.Vscrollbar widgets. Both are associated with an Adjustment object. The position of the thumb of the scrollbar is controlled by scroll adjustments. The attributes of adjustment object are used as follows −

PyGTK - Dialog Class

A Dialog widget is normally used as a pop-up window on top of a parent window. The objective of a Dialog is to collect some data from the user and send it to the parent window. Dialog can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed).

PyGTK - MessageDialog Class

A Messagedialog widget is a Dialog window configured to display an image representing the type of message, i.e., error, question, or some informational text. A MessageDialog object is declared by using the following constructor −
gtk.MessageDialog(parent = None, flags = 0, type = gtk.MESSAGE_INFO, 
   buttons = gtk.BUTTONS_NONE, message_format = None)

PyGTK - AboutDialog Class

A simple way to display information about a program like its logo, name, copyright, website and license is offered by the gtk.AboutDialog widget. An about dialog is typically opened when the user selects the About option from the Help menu. All parts of the dialog are optional.
The About Dialog can contain URLs and email addresses. gtk.AboutDialog offers global hooks when the user clicks URLs and email ID

PyGTK - Font Selection Dialog

The gtk.FontSelection widget allows users to select and apply the font of a particular name, size and style. The dialog has a preview box containing some text which will be displayed in selected font description, and two buttons CANCEL and OK.

PyGTK - Color Selection Dialog

This is a preconfigured Dialog in PyGTK API which lets the user to select and apply color. It internally embeds a gtk.ColorSelection widget.
The gtk.ColorScelection widget presents a colow wheel, and entry boxes for color parameters such as HSV and RGB. New color can be selected by manipulating color wheel or entering color parameters. Its get_current_color is useful for further processing.

PyGTK - File Chooser Dialog

This dialog is useful to let the user select the location and the name of file that needs to be opened or saved. It embeds FileChooserWidget and provides OK and CANCEL buttons in the action_area.
The following is a constructor of the gtk.FileChooserDialog class −
Dlg=gtk.FileChooserDialog (title = None, parent = None, 
   action = gtk.FILE_CHOOSER_ACTION_OPEN,  buttons = None, backend = None)
The parameters are −

PyGTK - Notebook Class

Notebook widget is a tabbed container. Each tab in this container holds a different page and the pages are seen in overlapped manner. Any desired page is made visible by clicking on the label of the tab. The labels can be configured to be displayed on top or bottom or to the left or right. A container widget with other widgets placed in it or a single widget is placed under each page.

PyGTK - Frame Class

Frame class is a subclass of the gtk.Bin class. It draws a decorative border around the child widget placed in it. The frame may contain a label whose position may be customized.
A gtk.Frame object is constructed with the help of the following constructor −
frame = gtk.Frame(label = None)

PyGTK - AspectFrame Class

gtk.AspectFrame class is a subclass of the Frame class. The child widget in this frame always retains its aspect ratio (of width and height) even if the main window is resized.
The ratio property of gtk.AspectFrame widget determines the widget width:height ratio. An aspect ratio of 0.5 means the width is one half the height; an aspect ratio of 2.0 means the width is twice the height. The default value for the "ratio" property is 1.0.

PyGTK - TreeView Class

The Treeview widget displays contents of a model implementing the gtk.TreeModel interface. PyGTK provides the following types of models −
  • gtk.ListStore
  • gtk.TreeStore
  • gtk.TreeModelSort

PyGTK - Paned Class

Paned class is the base class for widgets which can display two adjustable panes either horizontally (gtk.Hpaned) or vertically (gtk.Vpaned). Child widgets to panes are added by using pack1() and pack2() methods.
Paned widget draws a separator slider between two panes and provides a handle to adjust their relative width/height. If the resize property of child widget inside a pane is set to True, it will resize according to the size of the panes.

PyGTK - Statusbar Class

A notification area, usually at the bottom of a window is called the status bar. Any type of status change message can be displayed on the status bar. It also has a grip using which it can be resized.
The gtk.Statusbar widget maintains a stack of messages. Hence, new message gets displayed on top of the current message. If it is popped, earlier message will be visible again. Source of the message must be identified by context_id to identify it uniquely.

PyGTK - ProgressBar Class

Progress bars are used to give user the visual indication of a long running process. The gtk.ProgressBar widget can be used in two modes — percentage mode and activity mode.
When it is possible to accurately estimate how much of work is pending to be completed, the progress bar can be used in percentage mode, and the user sees an incremental bar showing percentage of completed job.

PyGTK - Viewport Class

If a widget has an area larger than that of the toplevel window, it is associated with a ViewPort container. A gtk.Viewport widget provides adjustment capability to be used in a ScrolledWindow. A Label widget for instance, doesn't have any adjustments. Hence it needs a Viewport. Some widgets have a native scrolling support. But a Label or a gtk.Table widget doesn't have an in-built scrolling support. Hence they must use Viewport.

PyGTK - ScrolledWindow Class

Scrolled window is created to access other widget of area larger than parent window. Some widgets like TreeView and TextView of native support for scrolling. For others such as Label or Table, a Viewport should be provided.
The following syntax is used for the constructor of the gtk.ScrolledWindow class −
sw = gtk.ScrolledWindow(hadj, vadj)
The following are the methods of the gtk.ScrolledWindow class −

PyGTK - Arrow Class

The gtk.Arrow object is used to draw simple arrow pointing towards four cardinal directions. This class is inherited from the gtk.Misc class and the object will occupy any space allocated it, for instance, a Label or Button widget.
Typically, Arrow object is created using the following constructor −
Arr = gtk.Arrow(arrow_type, shadow_type)
The predefined arrow_type constants are −

PyGTK - Image Class

This class is also inherited from the gtk.Misc class. The object of the gtk.Image class displays an image. Usually, the image is to be loaded from a file in a pixel buffer representing gtk.gdk.Pixbuf class. Instead a convenience function set_from_file() is commonly used to display image data from file in a gk.Image widget.

PyGTK - DrawingArea Class

The DrawingArea widget presents a blank canvas containing a gtk.gdk.Window on which objects such as line, rectangle, arc, etc. can be drawn.
PyGTK uses Cairo library for such drawing operations. Cairo is a popular 2D vector graphics library. It is written in C., although, it has bindings in most Languages such as C++, Java, Python, PHP etc. Cairo library can be used to draw on standard output devices in various operating systems. It can also be used to create PDF, SVG and post-script files.

PyGTK - SpinButton Class

The SpinnButton widget, often called the Spinner is a gtk.Entry widget with up and down arrows on its right. A user can type in a numeric value directly in it or increment or decrement using up and down arrows. The gtk.SpinButton class is inherited from the gtk.Entry class. It uses a gtk.Adjustment object with which the range and step of the numeric value in the spinner can be restricted.

PyGTK - Calendar Class

The Calendar widget in PyGTK toolkit displays a simple calendar with one month view at a time. The navigation controls to change month and year are displayed by default. The display options can be suitably configured.

PyGTK - Clipboard Class

A Clipboard object holds shared data between two processes or two widgets of the same application. The gtk.Clipboard is a high level interface for the gtk.SelectionData class.
The following is a prototype of the gtk.Clipboard constructor −
gtk.Clipboard(display,selction)

PyGTK - Ruler Class

This is a base class for horizontal (gtk.Hruler) and vertical (gtk.Vruler) rulers that are useful to show mouse pointer's position in window. A small triangle in the ruler indicates the location of pointer.
Ruler objects are created with their respective constructors −
hrule = gtk.Hruler()
vrule = gtk.Vruler()

PyGTK - Timeout

The gobject module of the PyGTK API has a useful function to create a timeout function that will be called periodically.
source_id = gobject.timeout_add(interval, function, …)
The second argument is the callback function you wish to have called after every millisecond which is the value of the first argument – interval. Additional arguments may be passed to the callback as function data.
The return value of this function is source_id.

PyGTK - Drag and Drop

Widgets having associated X Window are capable of drag and drop. In the program, a widget as a source and/or destination for drag-and-drop must first be designated. The widget defined as source can send out the dragged data. The destination widget accepts it when dragged data is dropped on it.
The following steps are involved in setting up a drag-and-drop enabled application −

PyGTK - Quick Guide

PyGTK - Introduction

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. Python bindings for other popular GUI libraries are also available.

PyGTK - Useful Resources

The following resources contain additional information on PyGTK. Please use them to get more in-depth knowledge on this.

Useful Links on PyGTK

Discuss PyGTK

PyGTK is a set of wrappers written in Python and C for GTK + GUI library. It is part of the GNOME project. It offers comprehensive tools for building desktop applications in Python. This tutorial discusses the basic functionalities of the different widgets found in the toolkit.