2.2. Theory of Signals and Callbacks

Before we look in detail at helloworld, we'll discuss signals and callbacks. GTK is an event driven toolkit, which means it will sleep in gtk.mainloop() until an event occurs and control is passed to the appropriate function.

This passing of control is done using the idea of "signals". (Note that these signals are not the same as the Unix system signals, and are not implemented using them, although the terminology is almost identical.) When an event occurs, such as the press of a mouse button, the appropriate signal will be "emitted" by the widget that was pressed. This is how GTK does most of its useful work. There are signals that all widgets inherit, such as "destroy", and there are signals that are widget specific, such as "toggled" on a toggle button.

To make a button perform an action, we set up a signal handler to catch these signals and call the appropriate function. This is done by using a GtkWidget  method such as:
 
handler_id = object.connect(name, func, func_data)

where object is the GtkWidget instance which will be emitting the signal, and the first argument name is a string containing the name of the signal you wish to catch. The second argument is the function you wish to be called when it is caught, and the third, the data you wish to pass to this function. The method returns a handler_id that can be used to disconnect or block the handler.

The function specified in the third argument is called a "callback function", and should generally be of the form
 
def callback_func(widget, callback_data):

where the first argument will be a pointer to the widget that emitted the signal, and the second a pointer to the data given as the last argument to the connect() method as shown above.

If the callback function is an object method then it will have the general form
 
def callback_meth(self, widget, callback_data):
where self is the object instance invoking the method. This is the form used in the helloworld example program.

Note that the above form for a signal callback function declaration is only a general guide, as some widget specific signals generate different calling parameters. For example, the GtkCList "select_row" signal provides both row and column parameters.

Another method call used in the helloworld example, is:
 
object.connect_object(name, func, slot_object)

connect_object() is the same as connect() except that the callback function only uses one argument, a pointer to a PyGTK object. So when using this function to connect signals, the callback should be of the form
 
def callback_func(object):

where object is usually a widget. The connect_object() method is mostly used to invoke PyGTK functions that are directly mapped to GTK+ functions. Usually you will use the connect() method since you will be invoking your own functions or methods.