Creating a GUI using PyGTK and Glade
After spending some time creating a GUI using TKinter and having it be pretty easy, but getting frustrated by how linked my code and the GUI was, I decided to look into creating a GUI using another toolkit. After looking around at the options for a while I settled on using PyGTK and Glade
The reason I decided upon using these two technologies is because they are cross platform and using GLADE satisfies my wish to separate the code form the GUI.
If you’ve never heard of Glade before, it’s “a User Interface Builder for GTK+ and GNOME”. It generates XML files which describe the desired GUI.
I’ll let the pyGTK website describe what PyGTK is:
PyGTK provides a convenient wrapper for the GTK+ library for use in Python programs, taking care of many of the boring details such as managing memory and type casting. When combined with PyORBit and gnome-python, it can be used to write full featured Gnome applications.
So there you go, I’m writing this on my freshly installed Debian system. If you are running Debian, or a Debian based distribution getting PyGTK and Glade is pretty simple:
apt-get install python-gtk2 python-glade2
Now lets create our first simple GUI, this is what you will be greeted with when you first start GLADE:
What we need to do is press the “Window” button on the GLADE palette to create our base window. We can then edit the properties of the window in the Properties Window:
We’ll call our window MainWindow and we will set the title to be “Hello World… Again!”.
If you are used to using an integrated GUI builder, for example Visual Studio, using glade might feel a bit strange the first few times. Especially since you don’t actually place your controls anywhere you want on the screen, instead you “pack” them. Strangely enough (at least for me) it actually seems like this is the way the most GUI builders work and applications like Visual Studio are actually the odd ones.
Either way back to the tutorial, the first thing we are going to do is add a label to tell the user to click the button (of course we could just put this text on the button, but how much fun is only one widget?). Since GTK used containers to pack widgets the first thing that we need to do is add a container. We are going to place the label above the Button so we will use a Vertical Box with two rows. To add the vertical Box, simply click on it in the Glade Pallet, and then click on our main window. A small dialog will come up and ask you how many rows you want, we want two in this case.
The next thing we’ll do is add the label by clicking on the label button in the GLADE pallet and then click on the first row in the container that we just created. We’ll keep the default name (label1) but we will change the text to be: “Please click on the button!”. Changing the text is done in the Glade Properties window, which if you have not noticed by now, displays, and allows you to edit, the properties of the currently selected widget.
The next thing we’ll do is add a button in the same way that we added the Label widget except we will add it in the second row. We will call the button btnHelloWorld, and set it’s label to be “Click me!”
We now need to set our project options, I’m going to call this project “pyhelloworld” and save it in my projects/PyHelloWorld folder.
Note: Be sure to set the Visible option for the MainWindow to Yes, on the Common tab of the Window or your main window won’t be visible! This is especially important if you are using Glade3!
So that’s it, you’ll see in the PyHelloWorld folder, that two files have been created, one is the glade project file and has the .glade extension, and the other is our glade GUI XML file with the extension .gladep.
Now we need to create a python program that will load the glade file and display it. So in the same folder I am going to create a file called PyHelloWorld.py.

Now the first thing we are going to have to do is import all of the libraries that we need for our project:
#!/usr/bin/env python import sys try: import pygtk pygtk.require("2.0") except: pass try: import gtk import gtk.glade except: sys.exit(1)
The next thing that we need to do is create our main class, I’m going to call it HellowWorldGTK. The we will use the __init__ function to load our glade file:
class HellowWorldGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file self.gladefile = "pyhelloworld.glade" self.wTree = gtk.glade.XML(self.gladefile) #Get the Main Window, and connect the "destroy" event self.window = self.wTree.get_widget("MainWindow") if (self.window): self.window.connect("destroy", gtk.main_quit)
The first thing that we do (after defining the class) is specify the glade file that we are going to use and create a gtk.glade.XML object using our glade file. Here is a description of the object taken from the pyGTK2 reference:
This object represents an `instantiation’ of an XML interface description. When one of these objects is created, the XML file is read, and the interface is created. The gtk.glade.XML object then provides an interface for accessing the widgets in the interface by the names assigned to them inside the XML description.
The gtk.glade.XML object can also be used to connect handlers to the named signals in the description. Libglade also provides an interface by which it can look up the signal handler names in the program’s symbol table and automatically connect as many handlers up as it can that way.
So what we are doing when we create our gtk.glade.XML object is creating and loading our main interface.
The next thing that we go is get an instance to our main window and connect the “destroy” event with the get.main_quit() function. This basically quits our application when the main window is closed. Otherwise the application will continue to run when the main window is closed (which we obviously don’t want).
That’s it for our HellowWorldGTK class, the next thing that we need to do is create an instance of our class and then start the GTK main loop:
if __name__ == "__main__": hwg = HellowWorldGTK() gtk.main()
That’s it, pretty easy so far, if you run this file you will be greeted with our little GTK window that doesn’t do anything yet except quit properly when you close the window.

The next step is to connect the button click event to a function. To do this we will need to use Glade again to edit our interface.
In the main window we need to select our button object and then in the properties Window select the “Signals” tab. There we will add a new signal by clicking on the signal browse button (…) and selecting “clicked”. This will create a handler called “on_btnHelloWorld_clicked” by default. We could change the name of this handler if we wanted but for now the default is good enough.

That’s it for the work in Glade, now what we need to do is connect that event to something in our code. Fortunately this is pretty easily done using the gtk.glade.XML.signal_autoconnect function.
#Create our dictionay and connect it dic = { "on_btnHelloWorld_clicked" : self.btnHelloWorld_clicked, "on_MainWindow_destroy" : gtk.main_quit } self.wTree.signal_autoconnect(dic)
Basically the dictionary is created using the name of the event, and the function to connect it to. You can see that we connect our button’s click event with a new function, and that we connect the “on_MainWindow_destroy” event with the gtk.main_quit() function, this basically is a replacement for our earlier code that quit the program when the window is closed. Important: If you want to use that version of the dictionary you should go and add the destroy event to the main window in glade.
Note: Since this was missed by people I’ve added some images to make it more obvious what event to connect to:


The next thing to do is create our btnHelloWorld_clicked function to the HellowWorldGTK class:
def btnHelloWorld_clicked(self, widget): print "Hello World!"
Pretty simple! Now when we run it, and click on the “Click Me!” button we see “Hello World!” written our to the command line.
That’s it for this lesson, but so far I really like what I see working with PyGTK and Glade. Here is the full source:
#!/usr/bin/env python import sys try: import pygtk pygtk.require("2.0") except: pass try: import gtk import gtk.glade except: sys.exit(1) class HellowWorldGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file self.gladefile = "pyhelloworld.glade" self.wTree = gtk.glade.XML(self.gladefile) #Create our dictionay and connect it dic = { "on_btnHelloWorld_clicked" : self.btnHelloWorld_clicked, "on_MainWindow_destroy" : gtk.main_quit } self.wTree.signal_autoconnect(dic) def btnHelloWorld_clicked(self, widget): print "Hello World!" if __name__ == "__main__": hwg = HellowWorldGTK() gtk.main()
Helpful links:
http://www.linuxjournal.com/article/6586
http://www.async.com.br/~kiko/pygtk-web/articles/bitpodder/BitPodder.htm
http://www.linuxjournal.com/article/7421
http://www.pygtk.org/articles.html
http://www.pygtk.org/tutorial.html
Popularity: 92%
Related Posts






May 19th, 2006 at 5:01 pm
Nice tutorial. My way of learning python is similar to yours(I’m also C++ dev) but you picked nice topics like rss. PyGTK look really nice but i have Tk -> it’s ugly on win32 and not much better on linux. However on MacOS(your screens) it rocks! Keep bloging!
May 24th, 2006 at 2:36 am
The tutorial is good. I had spend hours to learn the initial steps of using pyGtk with glade. My aim is to create a cross platform application that can run on both windows and linux with minimum modification. I tried PHP-gtk, but found not up to my requirements. PyGtk is seems to meet my requirements. But there is no tutorial is available on advance features. This is creating difficulties. Keep up the work and blog as much as possible on the advanced features of PyGtk
May 24th, 2006 at 11:33 am
Nazgob - Hey thanks! Yeah I didn’t mind the way the TKinter looked on OS X but it definately wasn’t pretty on Windows or Linux, but the cool think about it is that it’s integrated into Python, so no one has to install anything extra.
Raju - Thanks, yeah that’s actually one of the reasons that I wrote this tutorial since there wasn’t much out there to help absolute beginners. I’m working on another tutorial now but it’s taking a bit longer then I expected since it’s taking me longer to figure certain things out!
May 24th, 2006 at 6:35 pm
Thanks !
Works fine on Win32 but make sure the libglade-2.0-0.dll and libxml2.dll are in your “Program Files/Common Files/GTK/2.0/bin” directory, else Glade won’t work and running the py file will generate errors.
May 25th, 2006 at 12:54 am
installation should be :
apt-get install python-gtk2 python-glade2
(replace ‘python-gtk’ with ‘python-gtk2′)
May 25th, 2006 at 8:23 am
Nat - Hey that’s great, I’ve been meaning to try this on Win32 but I haven’t got the chance. Glad to hear that it works, and thanks for the tip!
Baiju - Good catch! Thanks for the information, I’ll fix that.
May 31st, 2006 at 3:55 pm
Small hint for ppl who hate Glade UI(like me). Try Gideon Designer or Gazpacho -> they do same stuff.
May 31st, 2006 at 7:48 pm
[…] learning python one man’s journey into python… « Creating a GUI using PyGTK and Glade […]
May 31st, 2006 at 8:27 pm
Nazgob: I’ve been meaning to check out Gazpacho for a while now, I really like the idea of having all of the pallets in one main window, but I have never heard of Gideon, I’ll have to look into that, thanks!
June 4th, 2006 at 6:09 pm
It makes the tutorial slightly more GUI-oriented if you make the button change the label text instead of printing to the console:
def btnHelloWorld_clicked(self, widget):
lbl = self.wTree.get_widget(”label1″)
lbl.set_text(”Hello World!”)
June 5th, 2006 at 4:05 pm
hola espero que me puedan ayudar a ver como se valida un edit para los numericos y tambien los alfabeticos
June 8th, 2006 at 9:07 am
Syd - That’s a good idea, origianlly I just wrote “Hello World!” out to the console becuase I thought it was easier for people at that point. Adding a function to set the text of the label is a good idea, thanks!
Carolina: I’m sorry but I do not speak Spanish, or I don’t speak Spanish well enough to mention. I tried translating your comment using Altavistas Babel Fish but I could not understand the result…I think it was about validating the contents of an edit field?
Perhaps if you give me a little bit more information I will be able to help you out.
June 10th, 2006 at 10:16 am
I also needed to apt-get glade-2, and glade is invoked using the command $glade-2
June 12th, 2006 at 5:32 am
This was an excellent article. I’m a bit of a beginner both to Python and to glade, but this was very easy to follow and a good introduction from which to progress.
I’ve tried using Glade previously but my only experience with GUI programming is from high school days with visual studio, naturally, I freaked when presented glade’s widget packing.
Now I see how easy it is *slaps forehead*
June 14th, 2006 at 8:56 am
qwright - Hmm I’ll have to look into that maybe I had Glade2 installed on my system by default or from some previous work…thanks for the information!
Etheri - Thanks, I really wanted this tutorial to be simple and easy for beginners to understand. Something that would give them a nice base of GLADE and PyGTK without being too difficult to follow. Hopefully I came close!
June 20th, 2006 at 12:17 am
Y a ,pretty good to see tutorials like this.It is very much similar to visual studio does.Ok,good to see in linux.I too want to start with python and gnome development.So it will give me a good start
June 25th, 2006 at 9:02 am
hey i liked the tutorial but would love to see a tutorial expaining PYGTK installation on RPM based machine & then creating widgets.
gud tutorial anyways am going to statoff with pygtk soon.
July 27th, 2006 at 9:13 am
Hi, thanks for the tuto. Im starting with python cos im updating an application done by another guy. Im using Win32 and i get this at the begining:
self.wTree = gtk.glade.XML(self.gladefile, “mainWindow”)
RuntimeError: could not create GladeXML object
the libglade-2.0-0.dll and libxml2.dll are in your “Program Files/Common Files/GTK/2.0/bin”
anyone can help? thanks in advance!
July 27th, 2006 at 11:41 pm
Hi Diego,
First of have you seen this item in the PyGTK FAQ? It basically walks you through getting PyGTK working on Win32. If you haven’t seen it yet give it a read, and follow it’s instructions it should get you going.
If not how are you launching the Python script? I know on win32 and on Macs I’ve run into problems before with the current directory. Try browsing to the directory that your script is in from the command line and calling python from there.
Let me know if you are still having problems.
August 19th, 2006 at 12:31 pm
[…] Now you have the library installed. The next step is to create the GUI that we will use to interact with the library. The GUI will be created using Glade, if you are new to Glade or PyGTK you might want to read over my two turorials on the subject: Creating a GUI using PyGTK and Glade and Building an Application with PyGTK and Glade. […]
August 23rd, 2006 at 4:29 pm
Nice tutorial. I found a typo:
>…“on_MainWindow_destroy” event with the gtk.mainquit() function,…
gtk.mainquit() -> gtk.main_quit()
August 23rd, 2006 at 5:05 pm
Great tutorial. I found one more typo:
>on the label button in the GLADE balled and then…
GLADE balled -> GLADE pallet
August 24th, 2006 at 12:53 am
Some more (because I’m translating your post, I read your every word
)
(1) the default name (lable1) but we will
lable1 -> label1
(2) The we will use write the __init__ function
Then we will write…?
(3) That’s it for our HelloWorldGTK class,
HelloWorldGTK -> HellowWorldGTK
Here’s Japanese translation (under your CC license):
http://po3a.blogspot.com/2006/08/pygtk-glade-gui.html
August 24th, 2006 at 8:51 am
S. Tanabe! That’s great! Thanks for catching all those typos of mine (I’ve gotta work on that!) and a Japanese translation, fantastic!
I’m not sure if you know or not, but this tutorial is also hosted on the PyGTK website. How would you feel about allowing PyGTK to host or link to your tutorial? We’d have to talk to them, but I’m sure that they’re interested in getting translations of their tutorials.
Let me know how you feel about that, and thanks again!
August 24th, 2006 at 2:57 pm
>How would you feel about allowing PyGTK to host or link to your tutorial?
Sounds good. I will email them.
August 27th, 2006 at 8:01 pm
[…] Right, so how do we get this lot working inside a GUI? Well, again, its fairly simple. This section will make the assumption that you know how to get a Glade GUI working inside your Python program (see this excellent tutorial if you have not done this before). […]
August 27th, 2006 at 11:09 pm
I emailed them and now my translation is on PyGTK website.
One more thing that I noticed:
>one is the glade project file and has the .gladep extension, and the other is our glade GUI XML file with the extension .glade.
It looks like glade project file has .glade extension ane glade GUI XML file has .gladep.
August 28th, 2006 at 8:54 am
[…] Satoshi Tanabe has translated my Creating a GUI using PyGTK and Glade tutorial into Japanese! You can view the Japanese tutorial on his website: http://po3a.blogspot.com/2006/08/pygtk-glade-gui.html […]
September 3rd, 2006 at 11:08 am
Good catch Satoshi, I’ve fixed it up!
September 15th, 2006 at 6:47 am
thanks for mentioning http://www.ballview.org/Members/pi/poker-42.htm
September 29th, 2006 at 12:51 pm
Great tutorial. Very clear. I really love this site lots of Python info. One problem I had with this is that it really won’t quit properly. I have to stop it with Ctrl+C. I thought at first I typed it wrong but it still happens for me when I have copied the code.
Any ideas?
Thanks again
October 2nd, 2006 at 2:56 pm
I followed this tutorial and found that running ./pyHelloWorld.py created the window as desired, however once I closed Glade and tried the command again nothing happens?
Does this mean I always have to have Glade running for these programs work?
Thanks
October 2nd, 2006 at 3:16 pm
Hi Daniel,
It sounds like you have not connected the “destroy” event properly. You need to connect the windows “destroy” event to gtk.main_quit() somehow. In the example I do it two ways directly:
The other way that I do this is by adding a destroy event handler to the main window and then connecting it using the dictionary:
October 2nd, 2006 at 3:28 pm
Hi Paul,
You shouldn’t need Glade running in anyway for the code to run properly.
What I do sometimes is add a print comment to the start of each function, that way I can tell how far the program gets before it crash or hangs. So maybe try doing this and then let me know how far the program is getting before it hangs?
October 2nd, 2006 at 3:49 pm
I put prints throughtout and this is as far as it gets:
try:
import pygtk
pygtk.require(”2.0″)
print “##1″
when I type ./pyhelloworld.py all I get returned is
##1
then back to the prompt
October 2nd, 2006 at 3:56 pm
Hey Paul,
Hmm that is weird, do you have any prints in the “Main” area? i.e.
October 2nd, 2006 at 4:15 pm
Hi, I must say I was very excited about this tutorial and have been trying now for over a week to get anywhere with programming python to make GUI apps. I am an MS programmer by day so this really greaves me
I get no other output. I found the tutorial excellently writen and Glade a treat to use, but what I have done wrong I dont know?
Here is my code:
#!/usr/bin/env python
import sys
try:
import pygtk
pygtk.require(”2.0″)
print “##1″
except:
pass
print “##2″
try:
import gtk
import gtk.glade
print “##3″
except:
sys.exit(1)
print “##4″
class HelloWorldGTK:
“”"This is an Hello World GTK application”"”
def __init__(self):
#set the Glade file
self.gladefile = “pyhelloworld.glade” #1
print “#1″
self.wTree = gtk.glade.XML(self.gladefile) #2
print “#2″
#get the Main Window, and connect the “destroy” event
self.window = self.wTree.get_widget(”MainWindow”) #3
print “#3″
if(self.window):
self.window.connect(”destroy”, gtk.main_quit) #4
print “#4″
if __name__ == “__main__”:
hwg = HelloWorldGTK() #5
print “#5″
gtk.main() #6
print “#6″
Paul…..in hope
October 2nd, 2006 at 4:51 pm
I just copy/pasted the whole script from this page into a new file and ran it and same result!
I am running KDE with pyhton2.4 and python-gtk2 and libglade is installed too?
October 2nd, 2006 at 5:08 pm
Hi Paul,
After looking over your code I’m guessing that the problem has to do with the second batch of imports, try the following code and let me know what happens:
October 2nd, 2006 at 5:53 pm
Hi, I get this?
./pyhelloworld.py
Traceback (most recent call last):
File “./pyhelloworld.py”, line 7, in ?
import gtk.glade
ImportError: No module named glad
do you think I should install Ubuntu with Gnome instead of Kubuntu with KDE?
Thnx
October 3rd, 2006 at 6:15 am
diebjovhc
ulbltxleu jgjaciwtk ojxzdufvza avxhsoy
October 3rd, 2006 at 8:54 am
Hey Paul,
I think that you should be able to use Kubuntu just fine, you just need to install the python-glade2 package. Once you do that everything should work! Let me know if you are still having problems with it.
October 3rd, 2006 at 2:15 pm
Thanks for the reply. I have the link in the data dictionary. If I create a button and link it in the same way the button works. Top X does not work either way.
Any ideas why it won’t work with the X?
Thanks
October 3rd, 2006 at 3:23 pm
Hi,
well I’ll be buggered!!!
I removed Kubuntu and installed Ubuntu, before reading your last post.
I could not get on with Ubuntu period so reverted to Kubuntu and thought, this is it on last time!
I started from scratch and looked to see if I had python-glade2 installed, well we know the answer to that….I didn’t.
Did I read the line at the beginning of the tutorial:
apt-get install python-gtk2 python-glade2
Yeah, but I’m a man and see what I want to see, so the wife tells me. I had already installed python-gtk2 previously so whizzed by this not seeing the python-glade2 bit.
So end result…..
A perfectly working sample GUI written using Glade, gedit and python!
Thanks selsine for your help….I’m on my way
October 4th, 2006 at 7:21 pm
Daniel,
Hmm that is strange, what if you connect the Destroy event to another function so that we can test to make sure that it’s getting called:
with self.on_quit looking something like this:
If you don’t get “Quit has been called” being printed out to the command line it probably means that the “destroy” even was not properly configured in glad to map to “on_MainWindow_destroy”. So then you’ll have to go back into Glade, select the main window, and add a handler for the “destroy” event that maps to “on_MainWindow_destroy”
October 4th, 2006 at 7:22 pm
Hey Paul,
That’s great that you got it working, too bad you have to reinstall you operating system first! But I think anyone that’s programmed for any length of time has gone through similar pains!
Good luck!
November 22nd, 2006 at 3:28 am
[…] http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ […]
December 2nd, 2006 at 8:02 am
Don’t forget to create the Signal for destroy, Daniel.
Made the same mistake.
Think it is not mentioned in the Text!
December 2nd, 2006 at 10:17 am
For me doesn’t function…
I have ubunu, and python-gtk2, python-glade2
this is my script :
#!/usr/bin/env python
import sys
import pygtk
pygtk.require(”2.0″)
import gtk
import gtk.glade
class HelloWorldGTK:
“”"This is an Hello World GTK application”"”
def __init__(self):
#set the Glade file
print “#1″
self.gladefile = “pyhelloworld.glade” #1
print “#2″
self.wTree = gtk.glade.XML(self.gladefile) #2
#get the Main Window, and connect the “destroy” event
print “#3″
self.window = self.wTree.get_widget(”MainWindow”) #3
if(self.window):
print “#4″
self.window.connect(”destroy”, gtk.main_quit) #4
else:
print “#5″
if __name__ == “__main__”:
print “#6″
hwg = HelloWorldGTK() #6
print “#7″
gtk.main() #7
And this is the .glade file :
True
202
37
True
Please click on the button !!
61
22
100
34
True
Press ME !!
105
67
the python PyHelloWorld.py return this :
manuel@unix:~/Desktop$ python Py*.py
#6
#1
#2
#3
#4
#7
and then it doesn’t exit from the gtk.main() loop….
it seems function….but i can’t see any window….
:’(
December 4th, 2006 at 9:05 pm
Olga - Actually it is in the tutorial, but it’s only briefly mentioned. Since everyone keeps missing it I have tried to highlight it more. Hopefully this helps.
December 4th, 2006 at 9:14 pm
Manuel - I’m not sure what the problem is. I tested out your code with my own glade file (as it appears as though your glade project got mangled when you posted it since it is supposed to be XML) and it worked fine on my system.
The dialog came up, and then when I closed it, it exited properly. Perhaps try another PyGTK tutorial of mine, downloading the source directly and test to see if that one works? Hopefully that will help us figure out what sort of a problem you are having.
December 11th, 2006 at 1:21 pm
Happy to see an active forum going on in the present. I spent all of yesterday getting pygtk, GTK, and Glade set up on WinXP. I had trouble finding the EXE installation files (tar files are abundant), but they worked beautifully. I find the documentation very scarce. I would like to have much more information on widget properties (in addition to events) and how to get/set them in Python. Where is that?
I also have the above mentioned problem closing the glade windows when running them interactively, and it screws up the pythonwin properties. It’s seems to be a pygtk incompatibility. However, when I run them standalone, they exit OK.
December 13th, 2006 at 8:31 am
A simple and very good tutorial. As a contribution, I’ve translated it to French : http://daniel.coquette.free.fr/dotclear/index.php/post/2006/12/11/Creer-des-interfaces-graphique-avec-PyGTK-et-Glade
December 14th, 2006 at 12:28 am
Don - You can find the PyGTK documentation here, it’s lacking in examples in certain places but over all it’s a very good resource.
I also tested another PyGTK program that I have in the interactive interpreter and it quit just fine, I simply had to run gtk.main() after launching the program.
Also you can download PyGTK windows installers from the PyGTK downloads page.
December 14th, 2006 at 12:33 am
Yarod- That’s great! You should let the people at www.pygtk.org know so that they can put up a link to your translation on their articles page.
Thanks again!
December 17th, 2006 at 6:28 am
Hello!
First of all, thank you for helping us with this kind of article, it’s really good to get in the mood with simple articles like that!
I followed it step by step, but I got stuck, like Manuel, at the “displaying the first window” part…
I am using Ubuntu, too, and I check several times if both python-gtk2 and python-glade2 where installed, which is the case already.
I am using gedit, and Glade3. By the way, Glade3 only generates one .glade file, no .gladep file… is it normal?
I firstly typed the code, but nothing happened: there is no error nor warning, but it is stuck in the main loop, and nothing happens.
Then I tried to copy/paste your own code, and nothing worked either…
Finally, I checked your pyWine sample, unTARed it, and launched it… and it worked! The window appears and I can close it properly…
I really don’t understand what’s going on!
I wanted to uninstall/reinstall pythong-gtk2, but itś too risky, since a lot of softwares I am using are based on that library (QuodLibet, …)
Do you have any other idea? That’s too bad, because it’s really the first steps, and I don’t know why it is buggy, and there is nothing I can do!
December 29th, 2006 at 6:01 pm
Pierre, I have similar problem, I am running glade-3-2.91.0 and pygtk-2.10.0
A tutorial from http://www.pygtk.org/tutorial.html works fine.
When I run this tutorial it hangs with no error and theres no window displayed.
Could be a glade issue?
Any ideas?
January 12th, 2007 at 7:31 pm
I can’t get rid of the problem that Diego has/had. I’m on Fedora Core 6 and I really need Glade with Python and this is like the only Py-Glade tutorial on the web.
Stupid error. I only get it when running any python app that I made or is form this site, or in the examples. It doesn’t do it with Exaile!
Please, help if you can?
January 13th, 2007 at 6:50 pm
(in glade-3) You need to make the window visible. The option is available in the “Common” tab.
January 14th, 2007 at 5:16 am
Nice tutorial, simple and ‘avaible’ for total noob like me. now i know the basics and i can finally work with python and glade.
January 14th, 2007 at 9:48 am
Marko, thank you so much ! I can’t believe it was such a simple thing… but I was pretty sure it had something to deal with Glade itself, since it seemed to work with everything else…
I can keep going on with my Python GUI exploration…
Thank you!
Maybe the tutorial should need to be updated (like add a “don’t forget to enable the Visibility of the Window by activating it in the Common tab…”).
January 14th, 2007 at 8:48 pm
Can someone please help me to overcome this $#%& problem. I can not build a single application. Please. Here is the output that I get when I run WordPy 0.1:
python ‘/home/stojance/Desktop/WordPy_0_1.tar.gz_FILES/word.py’
(word.py:24226): libglade-WARNING **: could not find glade file ‘wordpy.glade’
Traceback (most recent call last):
File “/home/stojance/Desktop/WordPy_0_1.tar.gz_FILES/word.py”, line 495, in ?
word = WordPy()
File “/home/stojance/Desktop/WordPy_0_1.tar.gz_FILES/word.py”, line 63, in __init__
self.wTree = gtk.glade.XML(self.gladefile, “wndMain”)
RuntimeError: could not create GladeXML object
That is what I mostly get in other applications built with Glade and Python, except Exaile. I know that someone over there knows the answer so if you do please post it as a comment here or send me an e-mail at: sdimitrovski at gmail dot com. Thank you.
January 14th, 2007 at 9:02 pm
I seem to have found the problem. Just create a .sh file, I did wordpy.sh and entered the code:
#!/bin/sh
python word.py $@
#
January 15th, 2007 at 8:40 pm
Hi Pierre, roy, and Marko,
Sorry for not being able to respond for a while I was away on holidays, but thank you Marko for answering the Glade 3 problem!
I have added a note to the tutorial so that hopefully people in the future won’t run into this problem.
January 15th, 2007 at 8:51 pm
Hi Stojance,
I seems like your problem may be related to you not specifying the full path to your glade file, perhaps try something like this:
January 15th, 2007 at 8:54 pm
Hi Koorghan,
Thanks I’m glad that you liked the tutorial!
February 3rd, 2007 at 9:41 pm
Very good tutorial!
February 6th, 2007 at 9:08 pm
Hey Leo, thanks for saying so!
February 9th, 2007 at 10:35 am
hi
.but i have a question how to call a function with arguments when the button is pressed , i mean i want to call this function :
thank you for this tutorial, i just started learning pygtk but it take much time to make GUI with gtk directly in code so i searched for something like qt-designer and here i found this nice tutorial
def btnHelloWorld_clicked(self, widget, txt):
print “Hello World! %s” % txt
so how could i mention the argument txt :
dic = { “on_btnHelloWorld_clicked” : self.btnHelloWorld_clicked}
self.wTree.signal_autoconnect(dic)
thanks
February 14th, 2007 at 7:19 pm
Hi foxmjay,
It depends on what you want to do. A simple way would be to simple store the
text within the class and then reference it like so:
Another way would be to connect with the buttons “clicked” signal manually and set what the extra callback data should be. Generally I think if you were going to do this you would pass an object that contained some information. Take a look at this as an example:
The results from running this and clicking the button twice should be:
Hello World: TextHello World: New Text
I hope that helps!
February 17th, 2007 at 6:40 am
Hi selsine
thank you for the answer, i see now you got the button from the widget and you connect it with my Methode using the default way to connect a button with gtk
, thank you it’s really helpful i tried it and it worked perfectly.
tnx
February 17th, 2007 at 5:47 pm
[…] Creating a GUI using PyGTK and Glade […]
April 5th, 2007 at 8:18 am
The site looks great ! Thanks for all your help ( past, present and future !)
April 7th, 2007 at 3:21 pm
[…] Actualmente estoy siguiendo el tutorial en castellano sobre pyGTK que se puede encontrar en su página web. Necesito aprender a manejarme bien con esto para el proyecto, y es el paso en el que estoy ahora. Aunque podría directamente ponerme con Glade o Gazpacho, que son dos diseñadores de interfaces gráficas, prefiero primero aprender a crearlas con código a pelo, porque luego necesitaré manejarlas y así adquiero soltura. Así que mientras sigo el manual, que es un señor libro, también miro tutoriales sobre el manejo de Glade y como conectar las interfaces que se generan a nuestro código. Quizás la mejor página que he encontrado sobre el tema sea Learning Python con una serie de tutoriales en el idioma anglosajón, así que me he decidido a traducir (libremente, lo mejor que pueda xD) los que considere más interesantes lo mejor que pueda, pues me obliga a fijarme bien línea a línea. El código lo dejaré tal cual, excepto los comentarios que los traduciré y que añado la codificación de caracteres para las tildes y la ñ, y usaré sus capturas de pantalla, aunque por supuesto probaré antes cada ejemplo. Además traduzco el texto completo, por lo que algunas cosas obviamente no se refieren a mi, como comentarios sobre he usado esto o me he decidido por esto otro. Así que ya os dejo con este primer artículo, titulado originalmente Creating a GUI using PyGTK and Glade, y escrito por Mark Mruss: Después de gastar algún tiempo creando una GUI usando TKinter y habiendo sido bastante fácil, pero frustrándome por como se enlaza mi código y la GUI, decidí probar a crear una GUI usando otro toolkit. Tras echar un vistazo a las diferentes opciones durante un rato me decidí por usar PyGTK y […]
April 7th, 2007 at 3:34 pm
Hi!
I’ve translated the tutorial to spanish, thank you for your great job making it!
April 9th, 2007 at 8:14 am
Hi Lord Taran!
That’s great! You might want to let the people at pygtk.org know. Thanks a lot it looks great!
April 26th, 2007 at 5:09 am
thanks a lot for translating to spanish the tutorial!
April 30th, 2007 at 7:48 am
First of all my hearty congrats … this has been an excellent tutorial. I would like to mention something that may be correct ( I am not that good with glade
) . My python application was still running even after i connected the destroy_event of MainWindow (firstly using connect then connecting to the glade reference on_MainWindow_destroy to my Handler) but when i connected the delete event of the main window it worked properly.
May 2nd, 2007 at 8:21 am
Hi Sajin,
Hmm that’s interesting, when you are connecting you have to make sure that you are connecting with the “destroy” signal and not the “destroy_event” signal. This has tripped many people up in the past when they have tried to do this.
Let me know if that solves your problem!
May 4th, 2007 at 10:49 am
hey selsine. thanks, thats really great work!! but i would like to know if youre going to put more tutorials or examples on py & glade. it would be really nice because the Internet is lacking such things.
and i have a small advice. in the tutorial the part about quitting the program with main window destruction seems deficient.its appearant many guys got confused with it. i also had problem with that (i managed to solve however). it can be better to explicitly mention how to add the destroy signal (in glade, not in the python code, my problem was with this).
thanks again for your effort to help us.:))
everybody, have a nice day.
May 4th, 2007 at 10:59 am
Hi Caner,
Yeah I am always planning on putting up more python tutorials on whatever people want. Right now I’m working on the PyGTD tutorials, which are a mixture of PyGTK and application development tutorials/examples.
What I’m trying to do with them is provide examples for people who are searching for solutions, which is something that I do quite often.
Thanks for the suggestion, I’ve been meaning to go back and make the quit code more explicit, because you are right too many people seem to be getting tripped up on it.
If you have any suggestions on what sort of tutorials you’d like to see perhaps post them in the forums or drop me an email.
May 4th, 2007 at 11:19 pm
Yes that was the mistake i connected the destroy_event not the destroy signal. But i still have doubts remaining.
1. Why it didn’t close the running Python code when i connected destroy to gtk.main_quit as shown in your code.
2. When does the delete_event get called. Is it something analogous to destroy events of other object oriented languages ?(like c#)
3.As i am beginner in python i would like to know about memory management in python. (like Does it have a garbage collector for the heap ?)
This tutorial is helping me in a lot of ways …. I think python is the neatest and clearest way to a cross platform GUI Application.
May 5th, 2007 at 12:25 pm
Hi Sajin:
1) As far as I can tell the destroy_event signal never gets emitted, it may simply be a outdated leftover signal?
2) As far as I can tell the delete_event signal is sent by the window manager when a window (or widget) is going to be destroyed. At that point the application has the option to allow that signal to continue (return False from the handler) or to stop it by returning True from the handler.
Then the destroy_event is called when a widget is going to be destroyed, but at this point there is no option to allow the event to happen, the widget will be destroyed. This happens when the delete_event is allowed to continue or when the gtk_widget_destroy() function is called.
3) If you want to learn more about python memory management (which I don’t know much about) try some of these lings:
http://docs.python.org/api/memoryOverview.html
http://evanjones.ca/python-memory.html
May 19th, 2007 at 7:47 am
Great tutorial, simple and clear! I followed every step from it but when I’m trying to run the script I get the error:
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:66: Warning: ignoring sys.argv: it must be a list of strings
_gtk.init_check()
Were is the problem?
Thank you.
May 22nd, 2007 at 11:54 pm
Hmm it seems like there might be a problem or an incontestability with the version of python and the version of PyGTK that you have installed…
What does it say on like 66 of /var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py??
May 23rd, 2007 at 7:36 am
Same thing as in the error message: ” _gtk.init_check()”.
May 23rd, 2007 at 8:02 pm
Hmm what version of GTK are you running?
Also try adding some print statements into the code so that you can tell where exactly the execution of the program is erroring out. Perhaps a few near the top (around the import commands) and then some in the main area…
May 26th, 2007 at 7:21 am
Hello again!
I have GTK v.2.10.1. I inserted some print statements in the code, and here is the output:
ok import sys
ok import pygtk
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:66: Warning: ignoring sys.argv: it must be a list of strings
_gtk.init_check()
ok import gtk
ok import gtkglade
The Glade file is seted
From what i understand, the script is runing ok untill the “import pygtk” where the error message appears. After that it si importing the gtk and gtkglade module and then it sets the galde file. But after that I get the error: “Unhandled “name ’self’ is not defined” on line 37! Line 37 is >> dic = { “on_button1_clicked” : self.button1_clicked, What i did wrong know?
May 26th, 2007 at 7:50 am
It works! I made an error in my script. The message about sys.argv does not affect the script. I never saw the window because I forget to set it to visible (as you mentioned in your tutorial). Thx again for your great tutorial!
June 1st, 2007 at 2:32 am
First off, selsine THANK YOU. I’m new to the python/pygtk/libglade thing and this tutorial was an excellent starting point. I was astounded by the complete lack of documentation available for this toolset until I finally came across your site. Props also for responding to all the feedback and updating the tutorial to reflect the issues that others have encountered.
That being said, I experienced the same problem as Daniel and Sajin above (running Ubuntu 7.04). Clicking the Main Window ‘X’ button caused the window to vanish, but I would have to Ctrl+C to exit.
My Solution:
In the ‘Signals’ tab of the Main Window properties (in both Gazpacho and Glade-3) there are 5 top level menus in the Signal column: GtkWindow, GtkContainer, GtkWidget, GtkObject, GObject.
Originally, I had mapped ‘on_MainWindow_destroy’ to ‘GtkObject –> destroy’ and experienced the error. Mapping to ‘GtkWidget –> destroy-event’ solved the problem.
Hope this helps and thanks again!
June 4th, 2007 at 1:42 pm
Hi sica,
That’s great! I’m glad that you got everything working, sorry I didn’t get a chance to respond to your post, I was away from the computer for a spell.
June 5th, 2007 at 8:45 am
Hmm that’s interesting Kmak, I’m surprised that the GTKObject Destroy signal didn’t work for you. Were you getting the signal at all? I wonder if this is something that is changing in later versions of GTK? I’ll have to look into this a bit more to see if I have to change the tutorial further. Thanks for the information.
Thanks for the kind words as well, you hit on one of the reasons that I first started writing this blog. I like to learn from examples and I was having a hard time finding examples that I liked, so I decided to make my own.
June 18th, 2007 at 5:41 am
Pas mal du tout, à recommander
Works fine indeed
July 7th, 2007 at 3:27 pm
i need some help cause i am new to programming ,,i have winxp & i created the GUI using glade as described i copied the code an put it in python then pressed F5
i got this error “inconsistent indentation detected 1-your indentation is outright incorrect or 2-your indentation mixes tabs and spaces” so what’s wrong and what’s meant by “apt-get install python-gtk2 python-glade2″ and where am i supposed to write it.sorry guys but i am abeginner & i am really trying to learn
August 7th, 2007 at 11:34 am
Hello mos3ad, your problem it’s you have typed the code with wrong indentation, you probably hava a code like this:
you can see that line 3 and line 5 don’t have the same indentation, it should be:
August 7th, 2007 at 12:19 pm
Hi Fran,
Thanks for the post, I must have missed that comment!
Hi Mos3ad,
The apt-get code is for debian based linux distrobutions and isn’t designed for Windows XP. If you want to you PyGTK on Windows XP just follow the installation directions on the PyGTK website and it should all work out for you.
August 8th, 2007 at 12:09 pm
Hey bro,
Great post, but I think u forgot to take a deeper look at the glade designer because you can actually place what u want wherever u want, there is a widget or something that allows u to accomplish it (I don’t remember the name because I’ve been using glade like for a couple of hours) But anyway this post has been of great help.
Keep on posting (well I know you have)
August 8th, 2007 at 12:31 pm
Yeah you can place widgets in exact positions using Glade, but I found that this really isn’t necessary. It was just something that I had to get used to, for the most part I’ve found it’s best to play within the standard rules…but that doesn’t mean that you can’t!
August 17th, 2007 at 6:48 am
Hi,
Hey, this is a great tutorial. But I have a problem. When I insert notebook into the window, the running application doesn’t display it. I tried using glade-2 and glade-3, but it only display window and the menu bar only. Notebook is not visible. I used your example code. But if I insert calendar control instead of notebook it dispayed the calendar control.
Please, can anyone suggest a solution for this.
Thanks
August 17th, 2007 at 10:34 am
[…] 参考creating-a-gui-using-pygtk-and-glade编写了第一个应用。 […]
September 3rd, 2007 at 2:54 pm
Thanks for this tutorial….I am new to pyGTK and i was looking for some basic things….and i got the same…
Thanks Again!!
September 17th, 2007 at 7:49 pm
[…] Da dove cominciare? Inizialmente si può fare un’immersione in python e poi consultare il tutorial ufficiale. Un altra risorsa spiega come creare applicazioni GUI con Python e GTK (in inglese). […]
September 17th, 2007 at 10:47 pm
Thanks for the great intro to PyGTK+Glade. I have been convinced that this combo is right for me, but hadn’t learned how to use it until I found your tutorial. I replicated your trial program without issue, and learned a lot along the way.
I do, however have one curiosity, which is only remotely related to this tutorial. How do you get your syntax highlighted Python code embedded in text boxes? I would be very happy to learn how to do this with my own blog eventually. An email would be much appreciated, if you have the time. Don’t feel obligated.
September 23rd, 2007 at 10:19 am
Hi Milinda,
How are you trying to insert the notebook into your program? What happens when you try to insert the notebook? Do you get any errors or does it just not show up?
You might want to try asking on the forums so that more people can find it.
September 23rd, 2007 at 10:22 am
Hi Shrikrishna,
Thanks for the kind words!
September 23rd, 2007 at 10:53 am
HI Matt,
I use this plugin for the code highlighting and for the most part it’s been great, but I’m thinking of trying something else soon when I get more time!
October 11th, 2007 at 3:29 pm
Great tutorial. But since half the battle is getting set up properly with the modules and runtime, it’s probably not good to hide the import exceptions like that. Try it flat:
import sys
import pygtk; pygtk.require(”2.0″)
import gtk
import gtk.glade
If any part of the setup is funky, the traceback written to the console will be helpful in figuring out the problem.
October 21st, 2007 at 7:24 pm
[…] learning python » Blog Archive » Creating a GUI using PyGTK and Glade After spending some time creating a GUI using TKinter and having it be pretty easy, but getting frustrated by how linked my code and the GUI was, I decided to look into creating a GUI using ano