Rapid Application Development with Python and Glade
Listing 1. GladeGen produced this Python code from the XML file created in Glade.
#!/usr/bin/env python
#--------------------------------------------
# MathFlash.py
# Dave Reed
# 02/28/2004
#--------------------------------------------
import sys
from GladeWindow import *
#--------------------------------------------
class MathFlash(GladeWindow):
#----------------------------------------
def __init__(self):
''' '''
self.init()
#----------------------------------------
def init(self):
filename = 'mathflash.glade'
widget_list = [
'window1',
'plus_check',
'minus_check',
'multiply_check',
'divide_check',
'digits_spin',
'operators_spin',
'correct_entry',
'wrong_entry',
'pct_entry',
'problem_entry',
'answer_entry',
'submit_button',
'reset_button',
'exit_button',
'new_button',
'result_entry',
]
handlers = [
'on_operator_check_toggled',
'on_submit_button_clicked',
'on_reset_button_clicked',
'on_exit_button_clicked',
'on_new_button_clicked',
]
top_window = 'window1'
GladeWindow.__init__(self, filename,
top_window, widget_list,
handlers)
#----------------------------------------
def on_operator_check_toggled(self, *args):
pass
def on_submit_button_clicked(self, *args):
pass
def on_reset_button_clicked(self, *args):
pass
def on_exit_button_clicked(self, *args):
pass
def on_new_button_clicked(self, *args):
pass
#----------------------------------------
def main(argv):
w = MathFlash()
w.show()
gtk.main()
#----------------------------------------
if __name__ == '__main__':
main(sys.argv)
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
self.widgets['result_entry'].set_text('Correct')
else:
self.widgets['result_entry'].set_text(
'Wrong, the answer is %d' % ans)
self.show_results()
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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- Developer Poll
- Dart: a New Web Programming Experience
- What's the tweeting protocol?
- New Products
- Thanks for taking the time to
1 hour 5 min ago - Linux is good
3 hours 3 min ago - Reply to comment | Linux Journal
3 hours 20 min ago - Web Hosting IQ
3 hours 50 min ago - Web Hosting IQ
3 hours 50 min ago - Web Hosting IQ
3 hours 51 min ago - Reply to comment | Linux Journal
6 hours 52 min ago - play with linux? i think you mean work-around linux
15 hours 18 min ago - Where is Epistle?
15 hours 24 min ago - You forgot OwnCloud
15 hours 53 min ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
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.




Comments
I have a better solution...
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!
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
What about signal names which includes '-'
Here's my solution
-------------------
"""GWidget - Making use of glade files easier.
:See:
GWidget
"""
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::
on_widgetname__signalname
``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
variable.
:CVariables:
- `GLADE_FILE`: Path of the glade file to use.
- `TOPLEVEL_NAME`: Name of the toplevel widget.
"""
# Path of glade file
GLADE_FILE = None
# Toplevel widget name
TOPLEVEL_NAME = None
# 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):
"""
:Parameters:
- `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:
self.autoconnect_signals()
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
else:
connect_func = conn_func
sig_in = key.rfind('__')
if sig_in >sys.stderr, 'Unknown callback method %s' % key
continue
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)
else:
print >>sys.stderr, 'Handler error for [%s]. No such widget [%s]' % (key, wid_name)
def __getattr__(self, attr):
try:
# 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
raise
GladeGenConfig.py file is not python
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
Appears to be a binary file in the .tgz
Re: GladeGenConfig.py problem
It appears to have been fixed.
The author should have posted that here.