A Beginner's Guide to Using pyGTK and Glade
The theory behind using Glade and libglade is it wastes time to create your GUI using code. Sitting down and telling the Python interpreter where each widget goes, what color it is and what the defaults are is a huge time sink. Anyone who's programmed in Tcl/Tk has spent days doing this. Not only that, but changing a GUI created with code can be a massive undertaking at times. With Glade and libglade, instead of creating code, you create XML files and code links to those files wherever a button or an entry box or an output text buffer is located.
To start, you need Glade v2 if you don't have it already. Even if you do, you may want the latest version of it. Downloading and installing Glade v2 should be easy enough once you have GTK v2 development packages (the -devel RPMs) installed. However, for most people new to GUI development, the starting window for Glade is intimidatingly blank.
To begin your application, click the Window Icon. Now, you should have a big blank window on your screen (Figure 1).

Figure 1. The cross-hatched area in the starting window is a place to put another widget.
The important thing to learn about GUI development is there are basically two types of objects: widgets, such as labels and entry boxes and other things you can see, and containers for those widgets. Most likely, you will use one of three kinds of containers, the vertical box, the horizontal box or the table. To create complex layouts, its easiest to nest these containers together in whatever order you need. For example, click on the horizontal box icon. Clicking on the hatched area in window1 inserts three more areas where you can add widgets. Your new window1 should look like Figure 2.

Figure 2. A basic three-pane vbox with the top pane selected.
You now can select any of those three areas and further divide it with a vertical box. If you don't like the results, you always can go back and delete, cut and paste or change the number of boxes from the Properties menu (more on that later).

Figure 3. The top pane has been split by a two-pane hbox, which is selected.
You can use these sorts of primitives to create almost any sort of layout. Now that we have a beginning layout, we can fill it with widgets that actually do something. In this case, I'll fill them with a label, a text entry, a spinbutton and a button. At first this looks pretty ugly (Figure 4).

Figure 4. The initial window filled in with widgets.
Remember that GTK auto-adjusts the sizes of the finished product when it is displayed, so everything is packed together as tightly as possible. When the user drags the corner of the window, it's going to auto-expand as well. You can adjust these settings in the Properties window (go to the main Glade window and click View→Show Properties). The Properties window changes different values for different kinds of widgets. If the spinbutton is focused, for example, we see the options shown in Figure 5.

Figure 5. The Glade interface for changing a widget's properties is customized for each type of widget.
By changing the Value option, we can change what the spinbutton defaults to when displayed. Also important is to change the Max value. A common mistake is to change the Value to something high but forget the Max, which causes the spinbutton initially to display the default but then revert to the Max value when it is changed, confusing the user. In our case, we're going to use the spinbutton as a TCP port, so I'll set it to 65535, the minimum to 1 and the default to 80.
Then, focus on the label1 and change it to read Host:. By clicking on window1 in the main Glade window, you can focus on the entire window, allowing you to change its properties as well. You also can do this by bringing up the widget tree window and clicking on window1. Changing the name to serverinfo and the title to Server Info sets the titlebar and the internal Glade top-level widget name appropriately for this application.
If you go to the widget tree view and click on the hbox1, you can increase the spacing between Host: and the text-entry box. This may make it look a little nicer. Our finished GUI looks like Figure 6.

Figure 6. The GUI in Glade does not look exactly like it does when rendered, so don't worry about the size of the Host: area.
Normally, this would take only a few minutes to put together. After a bit of practice you'll find that putting together even the most complex GUIs using Glade can be accomplished in minutes. Compare that to the time it takes to type in all those Tk commands manually to do the same thing.
This GUI, of course, doesn't do anything yet. We need to write the Python code that loads the .glade file and does the actual work. In fact, I tend to write two Python files for each Glade-driven project. One file handles the GUI, and the other file doesn't know anything about that GUI. That way, porting from GTK v1 to GTK v2 or even to another GUI toolkit is easy.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
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
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| 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 |
- Dynamic DNS—an Object Lesson in Problem Solving
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- Readers' Choice Awards
- What's the tweeting protocol?
- BASH script to log IPs on public web server
2 hours 23 min ago - DynDNS
5 hours 59 min ago - Reply to comment | Linux Journal
6 hours 31 min ago - All the articles you talked
8 hours 55 min ago - All the articles you talked
8 hours 58 min ago - All the articles you talked
9 hours 2 sec ago - myip
13 hours 24 min ago - Keeping track of IP address
15 hours 15 min ago - Roll your own dynamic dns
20 hours 29 min ago - Please correct the URL for Salt Stack's web site
23 hours 40 min ago
Enter to Win an Adafruit Pi Cobbler Breakout 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 Pi Cobbler Breakout 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
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
glade c
how can be get the previous window on click of a button on current window in glade c???
Visibility
It seems with glade-3 visibility of GtkWindow is off by default. That means, if you do the steps outlined here and run the program you exactly see nothing. To turn visibility on, select the GtkWindow (serverinfo) in the tree view in glade, select the Common tab, and set Visible to Yes. Trivial, yes, but took me some time to find in this property zoo.
How to connect two windows in pygtk
I am recently working with python. I want to create a GUI where i want to appear one window after clicking on the button of another window. How can I do that?
And after calling one window I want the control should be gone to next window and it shouldn't remain on initial one.
Plz can anybody help me?
How to connect two windows in pygtk
I am recently working with python. I want to create a GUI where i want to appear one window after clicking on the button of another window. How can I do that?
And after calling one window I want the control should be gone to next window and it shouldn't remain on initial one.
Plz can anybody help me?
www.experl.com
... and you thought this guy _only_ did cutting-edge comsec research?
http://www.experl.com
starting appgui.py
rudi@snjo:~$ Prosjekter/prosjekt1/src/appgui.py
(appgui.py:5573): libglade-WARNING **: could not find glade file 'project1.glade'
Traceback (most recent call last):
File "Prosjekter/prosjekt1/src/appgui.py", line 66, in ?
app=appgui()
File "Prosjekter/prosjekt1/src/appgui.py", line 35, in __init__
self.wTree=gtk.glade.XML (gladefile,windowname)
RuntimeError: could not create GladeXML object
check the path of the glade file
same as Subject.
Heh
... and you thought this guy _only_ did cutting-edge comsec research?
Code???
It would be nice to know what to do with the bits of code your pasting in the tutorial.
As it is your pasting the code and saying 'hey, this is a piece of the program, goodluck with it!'
How are beginners like myself supposed to know where to place this code?
Other than that nice tutorial, for as far as I was able to follow it
Im getting Syntax Error
Im getting Syntax Error at
pygtk.require ...
already installed pygtk at ubuntu 6.06, including devel package... :<
ok now... new problem: if i
ok now... new problem: if i try to contact google.com it works, but if i try www.google.com it fails:
GtkWarning: gtk_text_buffer_emit_insert: assertion `g_utf8_validate (text, len, NULL)' failed
self.logwindow.insert_at_cursor(data,len(data))
Same problem, found fix
See here:
http://www.mail-archive.com/pygtk@daa.com.au/msg17911.html
Re: A Beginner's Guide to Using pyGTK and Glade
here's the code for the first section with corrected indents and comments:
#!/usr/bin/env python import sys try: import pygtk #tell pyGTK, if possible, that we want GTKv2 pygtk.require("2.0") except: #Some distributions come with GTK2, but not pyGTK pass try: import gtk import gtk.glade except: print "You need to install pyGTK or GTKv2 ", print "or set your PYTHONPATH correctly." print "try: export PYTHONPATH=", print "/usr/local/lib/python2.2/site-packages/" sys.exit(1) #now we have both gtk and gtk.glade imported #Also, we know we are running GTK v2 class appgui: def __init__(self): """ In this init we are going to display the main serverinfo window """ gladefile="project1.glade" windowname="serverinfo" self.wTree=gtk.glade.XML (gladefile,windowname) # we only have two callbacks to register, but # you could register any number, or use a # special class that automatically # registers all callbacks. If you wanted to pass # an argument, you would use a tuple like this: # dic = { "on button1_clicked" : # (self.button1_clicked, arg1,arg2) , ... dic = { "on_button1_clicked" : self.button1_clicked, "on_serverinfo_destroy" : (gtk.mainquit) } self.wTree.signal_autoconnect (dic) return #####CALLBACKS def button1_clicked(self,widget): print "button clicked" # we start the app like this... app=appgui() gtk.mainloop()Re: A Beginner's Guide to Using pyGTK and Glade
hmm, the actual post doesn't look like the preview and tags don't work. well here are the major mistakes:
(add a comment) # (self.button1_clicked, arg1,arg2) , ...
(add an indent) dic = { "on_button1_clicked" :
Re: A Beginner's Guide to Using pyGTK and Glade
Wow, this is awesome!!!
I'm having just a couple problems though.
-How do you add keyboard shortcuts?
-Whenever I run the program from a different directory (i.e. "../file.py") it can't find the Glade file and dies. How do you tell Python to look in the same directory the .py file is in?
Whenever I run the program fr
Whenever I run the program from a different directory (i.e. "../file.py") it can't find the Glade file and dies. How do you tell Python to look in the same directory the .py file is in?
sys.path[0]is the path of the directory where the python script was found. So you could add (example):
import sysgladefile = sys.path[0] + "/" + "project1.glade"
Re: A Beginner's Guide to Using pyGTK and Glade
I fiddled around for some hours, but repeatedly got the following error:
I cost me quite some time to find out that the windowname used in your app has to be the same as the one given to the window in glade. Here's a posting on that issue: http://mail.python.org/pipermail/tutor/2003-September/025114.html
Maybe it's worth mentioning, it seems to me like some common pitfall and maybe it saves others time as well as frustration.
So, the following two entries have to be the same:
.glade file:
widget class="GtkWindow" id="window1"
.py file:
windowname="window1"
sebas.
Thanks! I wasted an hour
Thanks! I wasted an hour trying to figure this out.
Thank you :-)
Thank you .... :-)
I was also trapped in that ...
--
psk
libglade-CRITICAL error
Thanks a lot, i have been trying to figure out what was causing this error forever. I couldn't find the file glade-xml.c on my system, so i had no idea where to go. thanks again.
Thanks a lot ! I got the sam
Thanks a lot !
I got the same problem and could solve it now
Re: A Beginner's Guide to Using pyGTK and Glade
Sorry...first time ever with python here, and I can't seem to make this work. When I add the lines
self.logwindowview=self.wTree.get_widget("textview1")
self.logwindow=gtk.TextBuffer(None)
self.logwindowview.set_buffer(self.logwindow)
I get an error when I try to run it:
Traceback (most recent call last):
File "./main.py", line 44, in ?
app=appgui()
File "./main.py", line 30, in __init__
self.logwindowview.set_buffer(self.logwindow)
AttributeError: 'NoneType' object has no attribute 'set_buffer'
The same thing happens when I replace the initialization of logwindowview with self.logwindowview=gtk.glade.XML(gladefile,"textview1"), except instead of "Nonetype object" I get "gtk.glade.XML object" in the error. Am I missing something?
Re: A Beginner's Guide to Using pyGTK and Glade
me too. i stopped at that point.
Re: A Beginner's Guide to Using pyGTK and Glade
nevermind....apparently Glade didn't believe me when I said "Save." Problem fixed!
Speed ??
I am always curious, how fast is it in the end compared to c/gtk+ or tcl/tk or tcl/gtk+ ?
Re: Speed ??
I don't know for sure, but just a guess there's probably not a very big difference since all the drawing and socket handling is still in C somewhere under all the Python code; I wouldn't imagine this particular app to be very different from it's C counterpart.
Re: Speed ??
The answer is "Fast Enough."
I don't notice the difference between pyGTK and a normal GTK app. Obviously it doens't load up quite as quickly, since it has to load all of Python, but on a reasonably fast machine, you can't tell.
Dave Aitel
Immunity, Inc.
explanation confuses vertical and horizontal boxes
The text confuses vertical and horizontal boxes. This is probably obvious, but I don't want anyone to be confused when the text says horizontal box when referring to figure 2, when it is in fact a vertical box. The text for figure 3 says vertical box but should say horizontal box.
Re: explanation confuses vertical and horizontal boxes
I was wondering about that!
MacOS
What about MacOs X?
Re: MacOS
as long as you have gtk and python installed (via fink or from source) and some sort of X server, it shouldn't be a problem
Re: MacOS
I've seen various GTK+ progs on Mac OS X, I'm sure it's possible.
Re: A Beginner's Guide to Using pyGTK and Glade
I was just discovering pyGtk and marvelous pyGlade, this quite complete and simple introduction comes at the right time ! (I just found a pyGlade tutorial which was too simple and written for glade1, and pyGtk faq is quite chaotic (that's also fun))
I like the eleguance of such a solution.
I would be interested in knowing how to pack a python application in a win32 installer.
thanks.
Alex
Re: A Beginner's Guide to Using pyGTK and Glade
Greate article, I was just about to start writing a ton of threading code since I had never heard of input_add(), thanks for saving me the trouble.
I think the time for Python based GTK2 apps is now. Two, or even one, year ago I wouldn't have chosen Python for my project because the dependencies were too many. But since Red Hat now codes all their configuration utilities with pyGTK2 I am confident that many will already have all the libraries installed and that the language bindings will continue to be maintained. If distributed properly there is no difference between a GTK app done in C or python from the end users point of view, as it should be.
Re: A Beginner's Guide to Using pyGTK and Glade
I'm getting an error when running.
First I think the following line should have been commented out.
(self.button1_clicked, arg1,arg2) , ...
Second I'm getting an the following error.
File "./serverinfo.py", line 47
self.wTree.signal_autoconnect (dic)
^
SyntaxError: invalid syntax
Any Ideas, at first I typed everything in. Thinking there must have been a typo somewhere, I copied and pasted from the site and still get that error.
Thanks,
John R. Tipton
I had a problem like this...
I had a problem like this and it was that I didn't finsh the dictionary on the line before off with a '}' . Maybe that's your problem.
Re: A Beginner's Guide to Using pyGTK and Glade
remember: indention matters in python.
the lines
dict = {...
self.wTree.signal_autoconnect (dic)
should be indented same as the
self.wTree=gtk.glade.XML (gladefile,windowname)
before
Re: A Beginner's Guide to Using pyGTK and Glade
Another option is to get the .tgz file from the ftp site mentioned at the end.
The code in the article (both online and in print) has been through some
sort of formatter which seems to not like Python..
Re: A Beginner's Guide to Using pyGTK and Glade
So how involved is it to roll out python, pygtk, gtk2 and your application for clients who use windows and have none of that installed? Is it a case of it being better for you to do it yourself or is there a neat automated way one could create an "installer"? I was going to use python + pygame for a recent project, but ended up doing it in C for ease of distribution (windows ppl just download a binary and run it).
Nick
Re: A Beginner's Guide to Using pyGTK and Glade
Personally, I make my clients "Do it themselves". This currently involves downloading three executables from public websites, and double-clicking on each of them in turn.
In other words, it is extremely easy. It does take a few megs, but we've all got a few megs to spare for Python, right?
There is an annoying gotcha or two with Win32, of course. My current favorite is that Win32 will let you listen on one port twice in a row. Aside from that minor issue though, the Win32 CANVAS (which is what the article is based on) runs exactly the same as the Linux CANVAS. This was an impotant design consideration for me when I started the project.
Dave Aitel
Immunity, Inc.
Re: A Beginner's Guide to Using pyGTK and Glade
"just for next time". Pygame games are easily turned into standalone binaries. If you use one of the free "installer" programs, no one will ever know it was written in python. There are already "shareware" style games written in python for windows users. examples? click and play!
SolarWolf (my humble game, exe installer)
http://www.pygame.org/shredwheat/solarwolf/
BaseGolf (a shareware one, exe installer)
http://alitius.com/games/basegolf/
Pathological (new retro puzzler, zipped exe)
http://pathological.sourceforge.net/
These were all done using the "py2exe" tool and various packaging/installer tools.
Re: A Beginner's Guide to Using pyGTK and Glade
Wow! They must have used a time machine to travel to the future to post this!
Re: A Beginner's Guide to Using pyGTK and Glade
Their dates have been wrong for years. They don't seem to care.
I thought it was funny the first time I posted the same crack, but everybody else ignored me, and I nobody's ever fixed it.
Anyways, welcome to Linux Journal, dude.
~Bitterman~
Re: A Beginner's Guide to Using pyGTK and Glade
This is a sample article from the September issue, so its official date is September 1. Magazines generally put out a given month's issue during the previous month. Why? Tradition.
And yes, we're going to publish the Linux drivers for the time machine.
Re: A Beginner's Guide to Using pyGTK and Glade
If you're considering writing an app. for GTK+ 1.2, keep in mind that the Python bindings for GTK+ 2 are actively maintained. If you encounter a bug in the old bindings, of which I'm sure there are a few, they will not likely be fixed.
A cool feature of the latest PyGTK release, 1.99.17, is support for custom widgets. GLADE's widget palette isn't complete, so you can add a placeholder with the name of a widget creation function. I use this to embed gnome-terminal's VTE terminal emulator widget.
You'll notice that GLADE's signal handler drop-down list contains the names of C functions, like gtk_widget_show(). You can take advantage of this by writing Python functions with the same name. I frequently use the following functions:
Define these before the call to signal_autoconnect() function and you can pass it the value of the built-in locals() function. No need to write your own mapping dictionary.
PyGTK is good stuff. If you've ever seen a GTK+ program written in C, you'll appreciate how elegant a comparable Python can be.
embed terminal in GTK window
You mention that
I have tried finding system documentation as well as googled for implementations of python-vte and the use of vte_terminal_new() but there are no examples at the time of writing.
Please elaborate with a brief example of how to embed a terminal in a GTK window.
Any chance of elaborating
Any chance of elaborating with a quick example of the glade file and initial python code.
Re: A Beginner's Guide to Using pyGTK and Glade
Can anyone can give an example of how to create a new widget using
custom widget
Re: A Beginner's Guide to Using pyGTK and Glade
One clarification regarding signal_autoconnect(): if you write straight-line procedural code, as you are likely to do when starting out, you can define your handler functions at the top level and pass locals() to signal_connect(). For example:
If your handlers are in a class, as in this article, you can pass self to signal_autoconnect(). For example: