Create User Interfaces with Glade

Mitch shows how to use gnome-python's libglade binding to build Python-based GUI applications with little manual coding.
Glade Project Files

Glade saves information about a project in an XML-formatted project file having a filename extension of .glade. Glade's use of XML makes it easy to build separate add-on tools that operate on project files, such as code generators for new programming languages.

The first time you save a new project, Glade presents you with a Project Options dialog. Most of the settings in the Project Options dialog matter only when you are using Glade to generate source code for your project. However, some settings, such as the project directory, are important even when you are just using Glade as a layout tool.

By default Glade assumes you want to save your new project under your login directory, in a subdirectory named Projects/project1. This is probably not what you want. I usually save the project in the directory in which Glade was started.

Fortunately, it's easy to reset the project directory. Just click the Browse... button to the right of the Project Directory entry field, and a dialog entitled Select the Project Directory appears. This dialog selects Glade's current working directory by default, so you can just click its OK button.

When you do so the Project Directory field in the Project Options dialog changes to the current working directory, and the Project Name field goes blank. Type in a new project name, and the Program Name and Project File fields update accordingly (see Figure 3). When you click OK, your project will be saved to the specified project file.

Figure 3. Project Options Dialog

Using libglade

Once you have created a Glade project file, you can use gnome-python's libglade module to create the visual hierarchy described in the project file and to gain programmatic access to the widgets in the hierarchy:

import libglade
loader = libglade.GladeXML ("", "window1")

The libglade library defines a class, GladeXML, which does most of the work. To load a widget hierarchy, instantiate GladeXML and pass it the name of the Glade project file, along with the name of the topmost widget that you want to load from the file.

Note that you can supply the name of any widget in the hierarchy, even if it's buried deeply within a top-level window. This makes it possible to partition complex visual hierarchies—for example, the pages of a complex notebook-based interface—across multiple Glade project files. It also makes it easy to handle projects with dynamic visual content, loading only the components that are appropriate at any given time.

Once you have loaded a widget hierarchy, GladeXML lets you look up specific widgets by name via the get_widget method. get_widget returns the widget you requested or “None” if the widget cannot be found:

window1 = loader.get_widget("window1")
if window1:
    window1.set_title("Hello, World!")
Connecting Signal Handlers

One of the most powerful features of GladeXML is that it can bind Python callable objects (methods, functions, etc.) to signal handlers named in a Glade project file. The signal_autoconnect method makes this possible.

signal_autoconnect takes one argument: a dictionary mapping signal handler names to Python callables. For each of the signal handlers you've defined in your Glade project file, signal_autoconnect looks up the corresponding Python callable in the supplied dictionary. If a matching entry is found it is bound to the signal. In other words, your Python callable gets installed as the signal handler:

def button1_click_handler(*args):
    print "Don't push that button!"
signal_handlers = {
    # Exit the main event loop when the user closes
      the main window.
    'on_window1_delete_event': gtk.mainquit,
    # Call button1_click_handler when the user clicks
    'on_button1_clicked': button1_click_handler

By itself, libglade greatly reduces the manual coding needed for a gnome-python application. Widget hierarchies can be laid out using Glade and loaded with just two or three lines of code, as opposed to the hundreds that would be needed to create them using direct pygtk calls. What's more, behaviors can be added simply by assembling a dictionary of Python callables and passing it to GladeXML.signal_autoconnect instead of repeatedly invoking widget connect methods.

libglade saves a lot of effort, but it could do more. For instance, large Python applications are often structured as a small main program and an associated collection of Python packages installed somewhere on the Python path. Maintenance costs would be reduced if the application's Glade project files could be stored together with its Python packages and “imported” at runtime via relative pathnames.

It would also be helpful if widgets could be accessed directly as instance variables of some sort of UI hierarchy object without having to be located via GladeXML.get_widget.

Finally, it should be possible to automate building a dictionary of the callables in an object's namespace and passing that dictionary to signal_autoconnect. This would allow clients to define signal handlers as object methods and avoid explicitly registering the handlers.

The following sections describe a module, GladeBase, that provides these features. GladeBase also recasts the services of libglade to fit the MVC (model view controller) design pattern (see Listing 1 at GladeBase has two principal exports: class UI and class Controller.