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.

The GladeGenConfig.py file allows customizations to specify the program author, the widget types you want put in the self.widgets dictionary and how the created Python code file should look. In the GladeGenConfig.py file provided, the widget types GtkWindow, GtkButton, GtkSpinButton, GtkCheckButton, GtkEntry, GtkCombo and GtkTextView are listed. It rarely is necessary to access a GtkLabel widget and the container widgets, so I have not included them in the include_widget_types list in GladeGenConfig.

The created MathFlash.py file contains methods for each of the callback functions with the Python no-op statement pass. The method is declared with the self parameter and *args for a variable length parameter list. In Python, *args allow the function/method to be passed as many parameters as the caller wants, and they are received in the calling function as a tuple. Most of the callbacks are passed the widget that the event occurred in and sometimes additional parameters specific to the event. The API reference available on the GTK Web site shows the exact parameters for each callback (see Resources). Now, we need to add code to the callbacks and any other code the program needs. For this program, about 60 additional lines of Python code result in the final MathFlash.py file. An experienced Glade user and Python programmer should be able to create the entire program from scratch in less than 30 minutes. For more complicated programs, the Model/View/Controller design pattern could be used. The code GladeGen produces would play the role of the controller.

Let's examine the callback on_submit_button_clicked to understand the details of how to use the PyGTK code GladeGen produces. Here is the Python code I wrote:

def on_submit_button_clicked(self, *args):

    prob = self.widgets['problem_entry'].get_text()
    ans = eval(prob)
    user = int(self.widgets['answer_entry'].get_text())
    self.total += 1
    if ans == user:
        self.correct += 1
            'Wrong, the answer is %d' % ans)

The C GTK API contains the function G_CONST_RETURN gchar* gtk_entry_get_text(GtkEntry *entry). Because Python is an object-oriented language, the bindings are set up as methods for the class. For the Python bindings, the gtk_ and widget name prefixes are removed from the name of the function and called with a Python instance of that widget. This same pattern applies to all of the GTK functions. Using the self.widgets instance, the corresponding Python call becomes self.widgets['problem_entry'].get_text(), where problem_entry is the name for the entry widget in the Glade XML file.

I then used the Python eval function to determine the answer to the problem. This is much simpler than writing my own parser to evaluate the expression. The usual rule that multiplication and division have a higher precedence than addition and subtraction applies. Use of the eval function can be a security issue if you allow the user to enter the string that is evaluated, but in this case our program is producing the string that is evaluated, so we do not need to worry about it.

If you modify the Glade XML file, you can rerun GladeGen and it will add any new callback methods without overwriting or losing any code you have written other than the init method, which you should never modify. GladeGen produces a new init method each time you run it. The init method contains the names of the widgets and callbacks, so anytime the Glade file is updated, it needs to be reproduced. In my case, I later added a button to reset the stats. When I reran GladeGen, it added an empty on_reset_button_clicked method and provided a new init method that listed the reset_button widget and on_reset_button_clicked callback. Because I am using libglade to create the interface at runtime, no additional modifications are necessary.



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.

One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix