Rapid Application Development with Python and Glade

Create and modify your Python application's GUI using the easy design tool Glade; then, automate the process of setting up event handlers.
How GladeGen Works

GladeGen first determines whether the specified module/file exists; if not, it creates a basic file with author information and a class definition. GladeGen then parses the Glade XML file and finds a list of widgets and handlers. Python provides the inspect module that allows a program to determine what functions, classes and methods an existing Python module contains and which lines correspond to each. GladeGen uses the inspect module to determine which callbacks have been written already so that they are not replaced with an empty callback method. GladeGen adds any new callbacks to the bottom of the class definition. The inspect module also allows GladeGen to determine which lines contain the init method and to replace them with a new init method containing all the widgets and handlers in the latest Glade XML file.

Python supports both the standard DOM and SAX interfaces for parsing XML files. The SAX interface is an event-driven model in which the user sets up functions to be called as XML tags are processed. The DOM interface reads the entire XML file into memory and provides functions for traversing the XML hierarchy and retrieving the information. For GladeGen, we wanted to extract only certain information from the XML file, so the DOM interface is simpler to use. Also, the size of a Glade XML file is small enough that reading the entire file into memory and generating the Python representation of it should not require a large amount of memory. Using the DOM interface, the get_xml method in the GladeGen class extracts the widget names and handler names from a Glade XML file using about 30 lines of Python code.


Glade and GladeGen automate much of the tedious, repetitive work that goes into creating graphical programs by removing the need to write code to create and store widgets and set up the callback functions. This allows for rapid application development of Python/GNOME/GTK applications. The finished Math Flash is shown in Figure 2. The GladeGen software can run on any system that supports Python and GTK, including Linux, UNIX, Mac OS X and Microsoft Windows.

Figure 2. Math Flash

A number of features could be added to this system. Instead of using the generic *args parameter for the created callback functions, the parameters could be specified explicitly, based on the widget and callback prototype. I also plan to add a graphical front end to the program for configuring the options in the GladeGenConfig.py file. The GladeGen software is released under the GPL. If anyone is interested in modifying/extending it, please let the author know.


Thanks to one of my students, Jeremiah Schilens, who worked on an earlier version of this project with me.

Resources for this article: /article/7558.

David Reed lives in Columbus, Ohio with his wife and two dogs. He has worked with UNIX systems since 1991 and Linux since 1997. He holds a PhD in volumetric graphics from The Ohio State University and currently teaches computer science at Capital University. Capital uses a mixture of Python, C++ and Java throughout its CS curriculum. David can be reached at dreed@capital.edu.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I have a better solution...

Anonymous's picture

In www.oneminutepython.com I show you how to develop an application in only one minute! It contains direct links to key (all open source) applications (python, wxpython etc.) and a template application.

You saved my day!

sharat87's picture

I am pulling my hair off for almost 4 hours as to why my gtk window is not appearing... it was because I did not write the window.show() statement. No blog/article I have found until now include that line. I even reinstalled my glade and python thinking the error was with them.

Thank a looooooot!!!

Shrikant Sharat

Re: Rapid Application Development with Python and Glade

Anonymous's picture

What about signal names which includes '-'

Here's my solution

"""GWidget - Making use of glade files easier.

import sys
import gtk
from gtk import glade
import gobject

class GWidget(object):
"""Wrapper for widgets in glade file.

Each toplevel widget in a glade file can be associated with a GWidget
class. Methods of that class if has prefix `on_`, are treated as
signal handlers for widgets under the tree of toplevel widget in
glade file. Signal handlers are of the form::

``signalname`` if contains hyphens should be replaced with
underscores. If signal handler method name additionally ends with
double underscore (__), then ``connect_after`` is used to connect
that method.

``on_quit`` method if defined will be connected to ``delete-event``
event of the toplevel widget.

Any widget in the glade file (comming under toplevel widget) can be
accessed as if there is an instance variable named by that widget name.
Toplevel widget is always accessible through the ``widget`` instance

- `GLADE_FILE`: Path of the glade file to use.
- `TOPLEVEL_NAME`: Name of the toplevel widget.

# Path of glade file
# Toplevel widget name

# Properties
gladexml = property(lambda self: self._gladexml, doc='GladeXML object')
widget = property(lambda self: self._widget, doc='Toplevel widget')

def __init__(self, autoconnect_now=True):
- `autoconnect_now`: If False, doesn't autoconnect signals
self._gladexml = glade.XML(self.GLADE_FILE, self.TOPLEVEL_NAME)
self._widget = self.gladexml.get_widget(self.TOPLEVEL_NAME)
if hasattr(self, 'on_quit'):
self._widget.connect('delete-event', self.on_quit)
self._widgets_cache = {} # Widgets are stored in cache for
# quicker future retrieval
if autoconnect_now:

def autoconnect_signals(self, prefix='on_'):
"""Autoconnect methods with unique format with widget actions.

See the class documentation string for more info.
conn_func = gobject.GObject.connect
conn_after_func = gobject.GObject.connect_after
wid_in = len(prefix)
for key in self.__class__.__dict__:
hdl = getattr(self, key)
if callable(hdl) and key.startswith(prefix):
# Assumption: signal names doesn't contain double-underscores
if key.endswith('__'):
key = key[:-2]
connect_func = conn_after_func
connect_func = conn_func
sig_in = key.rfind('__')
if sig_in >sys.stderr, 'Unknown callback method %s' % key
wid_name = key[wid_in:sig_in]
sig_name = key[sig_in+2:]
sig_name.replace('_', '-')
new_widget = self._gladexml.get_widget(wid_name) or getattr(self, wid_name)
if new_widget is not None:
connect_func(new_widget, sig_name, hdl)
print >>sys.stderr, 'Handler error for [%s]. No such widget [%s]' % (key, wid_name)

def __getattr__(self, attr):
# Return the Gtk widget if cached
return self._widgets_cache[attr]
except KeyError:
# Return widget from gladexml
new_widget = self._gladexml.get_widget(attr)
if new_widget is not None:
self._widgets_cache[attr] = new_widget
return new_widget
# AttributeError

GladeGenConfig.py file is not python

Anonymous's picture

The GladeGenConfig.py file is a gzip file according
to the "file" command.

When renamed with a gz suffix and unzipped the
resulting file is a tar file which contains...

-rwxrwxr-- jill/ljedit 10867 2004-04-21 10:27:26 GladeGen.py
-rwxrwxr-- jill/ljedit 4992 2004-04-21 10:27:26 GladeWindow.py
-rw-rw-r-- jill/ljedit 2438 2004-04-21 10:27:39 MathFlash-create.py
-rw-rw-r-- jill/ljedit 2170 2004-04-21 10:27:39 MathFlash-create-short-lines.py
-rw-rw-r-- jill/ljedit 25161 2004-04-21 10:27:52 mathflash.glade
-rw-rw-r-- jill/ljedit 279 2004-04-21 10:27:52 mathflash.gladep
-rwxrwxr-x jill/ljedit 4752 2004-04-21 10:27:39 MathFlash.py
-rwxrwxr-x jill/ljedit 4752 2004-04-21 10:27:39 MathFlash.py-latest

But still no GladeGenConfig.py file....

GladeGenConfig.py problem

Anonymous's picture

Appears to be a binary file in the .tgz

Re: GladeGenConfig.py problem

Anonymous's picture

It appears to have been fixed.
The author should have posted that here.

Geek Guide
The DevOps Toolbox

Tools and Technologies for Scale and Reliability
by Linux Journal Editor Bill Childers

Get your free copy today

Sponsored by IBM

Upcoming Webinar
8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
11am CDT, April 29th
Moderated by Linux Journal Contributor Mike Diehl

Sign up now

Sponsored by Skybot