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:

Python RSS Reader

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:

Python RSS Reader

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.

Python RSS Reader

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.

PyGame Window

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.

PyGame 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.

PyGame Window

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:

PyGTK Window

Glade Window

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

selsine

del.icio.us del.icio.us

168 Responses to “Creating a GUI using PyGTK and Glade”

  1. Nazgob
    Says:

    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!

  2. Raju
    Says:

    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

  3. selsine

    selsine
    Says:

    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!

  4. Nat
    Says:

    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.

  5. Baiju M
    Says:

    installation should be :

    apt-get install python-gtk2 python-glade2

    (replace ‘python-gtk’ with ‘python-gtk2′)

  6. selsine

    selsine
    Says:

    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.

  7. Nazgob
    Says:

    Small hint for ppl who hate Glade UI(like me). Try Gideon Designer or Gazpacho -> they do same stuff.

  8. learning python » Blog Archive » Building an Application with PyGTK and Glade
    Says:

    [...] learning python one man’s journey into python… « Creating a GUI using PyGTK and Glade [...]

  9. selsine

    selsine
    Says:

    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!

  10. Syd
    Says:

    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!”)

  11. carolina
    Says:

    hola espero que me puedan ayudar a ver como se valida un edit para los numericos y tambien los alfabeticos

  12. selsine

    selsine
    Says:

    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.

  13. qwright
    Says:

    I also needed to apt-get glade-2, and glade is invoked using the command $glade-2

  14. Etheri
    Says:

    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*

  15. selsine

    selsine
    Says:

    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!

  16. U M A R
    Says:

    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

  17. atul jha
    Says:

    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.

  18. Diego
    Says:

    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!

  19. selsine

    selsine
    Says:

    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.

  20. learning python » Blog Archive » Wordpress Python Library
    Says:

    [...] 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. [...]

  21. S. Tanabe
    Says:

    Nice tutorial. I found a typo:

    >…“on_MainWindow_destroy” event with the gtk.mainquit() function,…

    gtk.mainquit() -> gtk.main_quit()

  22. S. Tanabe
    Says:

    Great tutorial. I found one more typo:

    >on the label button in the GLADE balled and then…

    GLADE balled -> GLADE pallet

  23. S. Tanabe
    Says:

    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

  24. selsine

    selsine
    Says:

    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!

  25. S. Tanabe
    Says:

    >How would you feel about allowing PyGTK to host or link to your tutorial?

    Sounds good. I will email them.

  26. jonobacon@home » Getting started with GStreamer with Python
    Says:

    [...] 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). [...]

  27. S. Tanabe
    Says:

    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.

  28. learning python » Blog Archive » Japanese translation!
    Says:

    [...] 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 [...]

  29. selsine

    selsine
    Says:

    Good catch Satoshi, I’ve fixed it up!

  30. Maureen
    Says:

    thanks for mentioning http://www.ballview.org/Members/pi/poker-42.htm

  31. Daniel
    Says:

    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

  32. Paul
    Says:

    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

  33. selsine

    selsine
    Says:

    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:

    self.window.connect("destroy", gtk.main_quit)

    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:

    #Create our dictionaty and connect it
    dic = { "on_btnHelloWorld_clicked" : self.btnHelloWorld_clicked,
    			"on_MainWindow_destroy" : gtk.main_quit }
  34. selsine

    selsine
    Says:

    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?

  35. Paul
    Says:

    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

  36. selsine

    selsine
    Says:

    Hey Paul,

    Hmm that is weird, do you have any prints in the “Main” area? i.e.

    if __name__ == "__main__":
            print "Main - 1"
    	hwg = HellowWorldGTK()
            print "Main - 2"
    	gtk.main()
  37. Paul
    Says:

    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

  38. Paul
    Says:

    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?

  39. selsine

    selsine
    Says:

    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:

    #!/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
  40. Paul
    Says:

    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

  41. smqsfu
    Says:

    diebjovhc

    ulbltxleu jgjaciwtk ojxzdufvza avxhsoy

  42. selsine

    selsine
    Says:

    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.

  43. Daniel
    Says:

    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

  44. Paul
    Says:

    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 :) :) :)

  45. selsine

    selsine
    Says:

    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:

    #Create our dictionaty and connect it
    dic = { "on_btnHelloWorld_clicked" : self.btnHelloWorld_clicked,
    		"on_MainWindow_destroy" : self.on_quit }

    with self.on_quit looking something like this:

    def on_quit(self, widget):
    	print "Quit has been called"
    	gtk.main_quit()

    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”

  46. selsine

    selsine
    Says:

    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!

  47. akuma » Blog Archive » classified
    Says:

    [...] http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ [...]

  48. olga
    Says:

    Don’t forget to create the Signal for destroy, Daniel.

    Made the same mistake.

    Think it is not mentioned in the Text!

  49. Manuel
    Says:

    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….

    :’(

  50. selsine

    selsine
    Says:

    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.

  51. selsine

    selsine
    Says:

    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.

  52. Don
    Says:

    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.

  53. Yarod
    Says:

    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

  54. selsine

    selsine
    Says:

    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.

  55. selsine

    selsine
    Says:

    Yarod- That’s great! You should let the people at http://www.pygtk.org know so that they can put up a link to your translation on their articles page.

    Thanks again!

  56. Pierre
    Says:

    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!

  57. roy
    Says:

    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?

  58. Stojance Dimitrovski
    Says:

    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?

  59. Marko Anastasov
    Says:

    (in glade-3) You need to make the window visible. The option is available in the “Common” tab.

  60. Koorghan
    Says:

    Nice tutorial, simple and ‘avaible’ for total noob like me. now i know the basics and i can finally work with python and glade.

  61. Pierre
    Says:

    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…”).

  62. Stojance Dimitrovski
    Says:

    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.

  63. Stojance Dimitrovski
    Says:

    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 $@
    #

  64. selsine

    selsine
    Says:

    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.

  65. selsine

    selsine
    Says:

    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:

    self.gladefile = os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])), "pyhelloworld.glade")
  66. selsine

    selsine
    Says:

    Hi Koorghan,

    Thanks I’m glad that you liked the tutorial!

  67. Leo
    Says:

    Very good tutorial!

  68. selsine

    selsine
    Says:

    Hey Leo, thanks for saying so!

  69. foxmjay
    Says:

    hi
    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 :).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 :

    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

  70. selsine

    selsine
    Says:

    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:

    def btnHelloWorld_clicked(self, widget):
      print “Hello World! %s” % self.txt

    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:

    #!/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 simpleData(object):
    
    	def __init__(self, text):
    		self.text = text
    
    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_MainWindow_destroy" : gtk.main_quit }
    		self.wTree.signal_autoconnect(dic)
    
    		button = self.wTree.get_widget("btnHelloWorld")
    		button.connect("clicked", self.btnHelloWorld_clicked
    			, simpleData("Text"))
    
    	def btnHelloWorld_clicked(self, widget, data):
    		print "Hello World: ", data.text
    		data.text = "New Text"
    
    
    if __name__ == "__main__":
    	hwg = HellowWorldGTK()
    	gtk.main()

    The results from running this and clicking the button twice should be:

    Hello World: Text
    Hello World: New Text

    I hope that helps!

  71. foxmjay
    Says:

    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 :D, thank you it’s really helpful i tried it and it worked perfectly.

    tnx

  72. learning python » Blog Archive » PyLan a GTD todo application written in python and PyGTK - part one
    Says:

    [...] Creating a GUI using PyGTK and Glade [...]

  73. morganusvitus
    Says:

    The site looks great ! Thanks for all your help ( past, present and future !)

  74. Las Noyas de Taran
    Says:

    [...] 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 [...]

  75. Lord Taran
    Says:

    Hi!
    I’ve translated the tutorial to spanish, thank you for your great job making it!

  76. selsine

    selsine
    Says:

    Hi Lord Taran!

    That’s great! You might want to let the people at pygtk.org know. Thanks a lot it looks great!

  77. Jose
    Says:

    thanks a lot for translating to spanish the tutorial!

  78. Sajin Koroth
    Says:

    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.

  79. selsine

    selsine
    Says:

    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!

  80. caner
    Says:

    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.

  81. selsine

    selsine
    Says:

    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.

  82. Sajin Koroth
    Says:

    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. :)

  83. selsine

    selsine
    Says:

    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

  84. sica
    Says:

    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.

  85. selsine

    selsine
    Says:

    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??

  86. sica
    Says:

    Same thing as in the error message: ” _gtk.init_check()”.

  87. selsine

    selsine
    Says:

    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…

  88. sica
    Says:

    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?

  89. sica
    Says:

    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!

  90. kmak
    Says:

    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!

  91. selsine

    selsine
    Says:

    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.

  92. selsine

    selsine
    Says:

    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.

  93. Lou
    Says:

    Pas mal du tout, Ă  recommander
    Works fine indeed

  94. Mos3ad
    Says:

    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

  95. Fran
    Says:

    Hello mos3ad, your problem it’s you have typed the code with wrong indentation, you probably hava a code like this:

    def method1(self, widget):
         line 1
         line 2
            line 3
         if statement :
             line 4
               line 5

    you can see that line 3 and line 5 don’t have the same indentation, it should be:

    def method1(self, widget):
         line 1
         line 2
         line 3
         if statement :
             line 4
             line 5
         line6
  96. selsine

    selsine
    Says:

    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.

  97. JC Sandrea
    Says:

    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)

  98. selsine

    selsine
    Says:

    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!

  99. Milinda
    Says:

    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

  100. A New Day Has Come » Blog Archive » 学用pygtk+glade (1)
    Says:

    [...] 参考creating-a-gui-using-pygtk-and-glade编写了第一个应用。 [...]

  101. Shrikrishna
    Says:

    Thanks for this tutorial….I am new to pyGTK and i was looking for some basic things….and i got the same… :)

    Thanks Again!!

  102. It’s Not Just Software » Blog Archive » Python? wow, che linguaggio!
    Says:

    [...] 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). [...]

  103. Matt Nichols
    Says:

    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.

  104. selsine

    selsine
    Says:

    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.

  105. selsine

    selsine
    Says:

    Hi Shrikrishna,

    Thanks for the kind words!

  106. selsine

    selsine
    Says:

    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!

  107. Eric
    Says:

    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.

  108. links for 2007-10-22 « B-link List
    Says:

    [...] 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 another toolkit. After looking around at the options for a while (tags: python glade gtk programming tutorial gui pygtk) [...]

  109. Python? wow, che linguaggio! « It’s not just software
    Says:

    [...] 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). [...]

  110. ED Lubitz
    Says:

    Hi,

    My name is Ed, I am really new to Python. I have had it for…oh 3 days. Before attempting Python I did most of my Interfacing with JB. I am using Windows and my console looks slightly different than yours, in your tutorial. I get down as far as saving my project with the extensions Glade and Gladep. I have no Gladep in my folder. Do I need to get an xml editor as well. I am confused here!

    Big thanks

    Ed

  111. Python GUI « The Lumber Room
    Says:

    [...] That blog also has other posts like this and this, and searching for “pygtk” gives some more posts… Must look at it and learn it sometime. [...]

  112. selsine

    selsine
    Says:

    Hi Eric,

    You raise a very good point I have changed this sort of code in my later scripts. I realized how frustrating it was when I encounter problems. Thanks for the tip!.

  113. selsine

    selsine
    Says:

    Hi Ed,

    By this time I’m assuming that you are using Glade 3.0, and in Glade 3.0 you only get one file: a .glade file, so don’t worry that you done see a .gladep file.

  114. It’s Not Just Software » Python? wow, che linguaggio!
    Says:

    [...] 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). [...]

  115. Eero Tamminen
    Says:

    Instead of doing this manually in code:
    self.window.connect(“destroy”, gtk.main_quit)

    Just set it in Glade widget property dialog signals tab.

  116. selsine

    selsine
    Says:

    Hi Eero,

    Thanks for the tip!

  117. Mark
    Says:

    Thanks much for the tutorial. I didn’t actually get it to work but the syntax familiarization is helpful anyway.

  118. Petebow4
    Says:

    Great intro! It got me started on my project. The explanation of event handling was excellent!

  119. Shams
    Says:

    Great tutorial! I’m an absolute beginner when it comes to writing applications on Linux/Unix, but this tutorial did a good job in helping me write my first Linux application with a GUI. Hope to see more of this soon.

  120. Ben
    Says:

    Thanks! I’ve been looking around for a nice beginners tutorial. One trivial comment, in your python code the glade file is in lower case – pyhelloworld.glade, but in your tutorial you refer to saving it as PyHelloWorld.glade (which is what I saved it as). Because I cut and paste to create the program, rather than just compiling your files, the naming mismatch broke the program. I know it’s easy fixed…but might throw a real beginner

  121. selsine

    selsine
    Says:

    Hi Ben,

    Thanks for the catch, I’ve updated the tutorial. Happy hacking!

  122. Trundle
    Says:

    `pygtk.require` inside a try-except-block does not make no sense at all because `pygtk.require` raises an AssertionError if the required version doesn’t match with the versions installed, which would be caught by the except-block.

  123. selsine

    selsine
    Says:

    Hi Trundle,

    Thanks for the comment. In general I think it’s a mistake to have the imports in a try-except block the way that I do in this tutorial, unless it’s for an optional module. This tutorial is just a bit old and I thought I was being smart at the time. Thanks for the information!

  124. Fabio Varesano
    Says:

    Thank you for this guide.. it helped a lot doing my first steps in Python/GLADE programming! Thanks!

  125. Creating a GUI using PyGTK and Glade (from This Is The Goo I’ve Got)
    Says:

    [...] 6 June 2008 Creating a GUI using PyGTK and Glade The tutorial is a couple of years old, so a few things have changed in the meantime, but it’s [...]

  126. Derek
    Says:

    Hi, just wanted to say thanks – nice article.

    Coming from a .net, VB, c#, delphi background I found the interface quite alien to start with, but once I saw it as HTML (the layout is similar to the older style HTML) then it all made sense.

    I couldn’t get Glade/gtk2 working in Windows (something to do with a version of GIMP I think), but at home using Ubuntu (Gnome) it works just fine.

    Can’t wait to get really moving with this, so thank you once again.

  127. Conlaoch
    Says:

    There is also a utility called GladeGen. It is from a previous LinuxJournal article. It will take in a .glade file and create all of the skeleton code for you. Then all that needs to be done is to implement the signal handlers.

    I don’t know if it works with Glade 3 yet, but its saves a lot of time with Glade 2.

    Conlaoch

  128. selsine

    selsine
    Says:

    Hi Conlaoch,

    Thanks for the reply. I’ve seen/heard of GladGen before but I’ve never used it. Thanks for the information.

  129. Brin
    Says:

    Great idea for a tutorial; I just wish I could get a window to appear!

    I’m running xandros linux and have python-gtk2 and python-glade2 installed. The .py, .glade and the .gladep files are in the same folder. MainWindow is set to visible.

    Just can’t think of anything else!

  130. selsine

    selsine
    Says:

    Hi Brin,

    What happens when you run the code? Does it hang or does it just quit? You might try running the following code and seeing where it goes wrong:


    #!/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

  131. Brin
    Says:

    Hi….thanks for your reply. This did work and so looking more closely at my code I found that the def __init__(self): had not been indented and this was not trapped by python. Success at last!

    Incidentally I find that in addition to a .glade file I have .glade.bak plus two new folders po and src and several other files e.g. stamp-h.in. Are these documented anywhere and are they useful?

    Cheers…….Brin

  132. Mjrz
    Says:

    Hi,

    Great tutorial! I’ve been trying to make sense of how to use glade for a long time and not succeeding until I found your blog. Thanks!

  133. rio
    Says:

    hi selsine… thanks so much for your tutorial

    finally i can made a hello world using GLADE… :)

  134. Python and Gtk: PyGTK | lonerunners.net
    Says:

    [...] Creating a GUI using PyGTK and Glade [...]

  135. OLPC CS Course: Week 3 Pygtk Glade Development
    Says:

    [...] Portions of this were adapted from Creating a GUI using PyGTK and Glade [...]

  136. Why is it so hard? « Greg Auger • fluteflute
    Says:

    [...] Far more ‘easy’ documentation, examples and tutorials are needed. Some sites like learningpython.com are really useful, but if we are to attract more programmers to open source easier tutorials and [...]

  137. OLPC CS Course: Week 4 Pygtk Glade Dev Continued
    Says:

    [...] Portions of this were adapted from Creating a GUI using PyGTK and Glade [...]

  138. JonBob
    Says:

    Nice tutorial! I am new in programming with python. I did my first python experience with pyDev and eclipse on Windows machine.
    I am going through you tutorial and stack at the point when I have to save my project. I don’t have the option to save the project as python project. There are only possibilities for C, C++ and adda 95.
    Please give me a hint what I did wrong?

    Thank
    JonBob

    Sorry for the bad English … I am still learning ;-)

  139. selsine

    selsine
    Says:

    Hi JonBob,

    I’m not really sure. To be honest it’s been a long time since I used pyDev and eclipse. In the end I found it too cumbersome, try using geany, it’s my personal favourite these days.

  140. Peter
    Says:

    hi…thanks for the tutorial
    it really usefull for newbie like me.
    unfortunate, iam having trouble to create a python
    script that execute debian package.
    i have the example image here:
    http://www.freeimagehosting.net/uploads/b0157fe94c.jpg

  141. Maxe
    Says:

    Thanks a lot, mate. Good Tutorial to get started.

    Max

  142. Thomas Smith
    Says:

    Hi,

    I was having the same problem as some others, where the program wouldn’t quit after I destroyed the window and I had to press control-C. I figured out what was wrong with my code and I thought I would mention it. It was a dumb error, but…

    The main window of my application was not named “MainWindow”, it was named “window1″. So the line about self.wTree.get_widget(“MainWindow”) returned nothing. Then, since there was an if statement around self.window.connect(“destroy”, gtk.main_quit), it silently didn’t connect the event to anything. It might be clearer to leave out that if statement, so that if something’s wrong it’s easier to see it.

    Anyway, thanks so much for the tutorial! I’ve been wishing that I could find good GUI programming opportunities in Python, and this seems like a really good step in that direction.

    -Thomas

  143. selsine

    selsine
    Says:

    Hi THomas,

    Thanks for the information, I’m sure this will help other people if they run into a similar issue.

    mark.

  144. Bal
    Says:

    Hi, after following this tutorial, I’ve managed to make some small programs. Now I want one that edits a text file, by getting the contents of three text boxes then pasting them into the file. How would I go about this? I can guess, but I’d probably be wildly out. I don’t really need specifics, just the basic code needed in order to do so.

    Preferably by putting the contents of text boxes into a variable, then pasting the contents of the variable into the text file. I can do the latter part, but the former part stumps me. Any help would be appreciated.

    -Bal

  145. Lambda: For Those Who Grok: Gtk
    Says:

    [...] GTK and Glade [...]

  146. Drayze
    Says:

    Great tutorial. I’ve just started exploring python with glade-3. It works well after turning on \visible\ at the common tab. Also I have to save the glade file as libglade.

    Thanx for the tutorial!!!

    -Drayze

  147. Sajeev
    Says:

    Yes nice intro tutorial..Thank you..

    My .glade file is in the same folder as the .py.

    but python says that it can’t find the glade file .

    one of the posts above also deals with this..

    ….on Windows XP 32

    Everything works if I give a full path name.
    Not sure if this is the correct thing to do. Absolute beginner here:)

  148. anand
    Says:

    Simple and wonderful tutorial. Thanks a bunch for taking your time to post it.

    I did ran into the

    “RuntimeError: could not create GladeXML object” problem that @Diego and few others got. I am using Glade 3.6.3 on Ubuntu 9.04. The problem was with glade project file format. Glade 3.6.3 offers couple of options: GtkBuilder and libglade. To use it with PyGtk programs, the format should be “libglade” (by default GtkBuilder is selected). Changing this got the program running.

  149. MZ
    Says:

    libglade will be deprecated! You should use gtkBuilder instead!

    http://www.micahcarrick.com/05-30-2008/gtk-builder-libglade-faq.html
    http://www.pygtk.org/docs/pygtk/class-gtkbuilder.html

  150. Scott
    Says:

    Hi –

    Tried your code and originally got the window to appear, then tried to adjust the names to start building my own app and now the code runs and immediately terminates without error but never shows me a window. Here’s what I did:

    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 = “glade1.glade”
    self.wTree = gtk.glade.XML(self.gladefile)

    self.window = self.wTree.get_widget(“window1″)
    if (self.window):
    self.window.connect(“destroy”, gtk.main_quit)

    #Create our dictionay and connect it
    dic = { “on_button1_clicked” : self.button1_clicked,
    “on_window1_destroy” : gtk.main_quit }
    self.wTree.signal_autoconnect(dic)

    def button1_clicked(self, widget):
    print “Hello World!”

    if __name__ == “__main__”:
    hwg = HellowWorldGTK()
    gtk.main()

    Any thoughts?
    Thanks,
    Scott

  151. glade-pygtk tutorial?
    Says:

    [...] icin en guzel kaynak: http://www.pygtk.org/pygtk2tutorial/index.html glade ve pygtk icin: http://www.learningpython.com/2006/0…gtk-and-glade/ glade ve pygtk icin sunu da inceleyebilirsin: http://www.linuxjournal.com/article/6586 Mortal [...]

  152. Tshepang Lekhonkhobe
    Says:

    You mind updating this (GtkBuilder + new Glade UI)? It looks really good.

  153. Andreas
    Says:

    Thanks for the tutorial, it is a bit hard to read though(not really clear sections, can be annoying sometimes)

    Anyway, making my own application now with pygtk and glade, and I think it would be nice if you made clear that you need to modify other pieces of code that are plain pygtk.
    just like
    “hwg.hide()”
    doesn’t work normally here, but
    “hwg.wTree.get_widget(“MainWindow”).hide()”
    does. This is probably because of the parsing of glade to python.

  154. Pygmalion » Blog Archive » Default Glade window sizes
    Says:

    [...] The basics of creating a GUI using PyGTK and Glade: http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ [...]

  155. kotnik
    Says:

    @Scott,

    in Glade-3, main window is by default invisible. To see it, you need to select main window, go to Common tab and select Visible -> Yes.

  156. learning python » Blog Archive » New Belorussian/Belarusian Translation
    Says:

    [...] everyone, just a quick note to let you know that Bohdan has translated the Creating a GUI using PyGTK and Glade tutorial in to Belorussian/Belarusian. You can view the translation here: Belorussian [...]

  157. Rahul
    Says:

    when i run the following code.It shows the gui of treeview with only column name and nothing displayed content below it:-

    import pygtk
    pygtk.require(’2.0′)
    import gtk
    import gobject

    class Window:
    def __init__(self):
    self.builder = gtk.Builder()
    self.builder.add_from_file(‘Tree.xml’)
    self.main_window = self.builder.get_object(“window”)

    #getting the treeview from the widget tree
    self.H2EView =self.builder.get_object(“treeview”)

    dic= {“on_window_destroy”:self.quit}
    self.builder.connect_signals(dic)

    # adding column to the treeview
    self.add_column_name(” Hindi “,0)
    self.add_column_name(” English “,1)

    #Creating ListStore model and linking with treeview Object
    self.H2EList = gtk.ListStore(str,str)
    self.H2EView.set_model(self.H2EList)

    # Adding elemrnts to the table
    self.H2EList.append(["manDua" , "Ragi"])

    self.main_window.show_all()

    def add_column_name (self,title,columnId):
    column = gtk.TreeViewColumn(title, gtk.CellRendererText() ,text=columnId)
    column.set_resizable(True)
    column.set_sort_column_id(columnId)
    self.H2EView.append_column(gtk.TreeViewColumn(title))

    def quit(self, widget):
    print “Window closed”
    gtk.main_quit()

    def main():
    app = Window()
    gtk.main()

    if __name__ == “__main__”:
    main()

    and the following is the Tree.xml

    -

    – True False True – - True True automatic automatic – - True True

    kindly assist

  158. Libglade python | Fivedollarsbyt
    Says:

    [...] learning python » Blog Archive » Creating a GUI using PyGTK and …May 7, 2006 … I am running KDE with pyhton2.4 and python-gtk2 and libglade is installed too? selsine Says: October 2nd, 2006 at 5:08 pm. Hi Paul, … [...]

  159. Mark Tiddens
    Says:

    The Glade library is included in GTK now (called gtk.Builder), so the Glade library (Libglade) has been depreciated and is no longer needed. So, when you create a new project, choose “GtkBuilder” as your format rather than “Libglade”. And then you can remove all references and use of .glade in your code, with the result as follows:

    import sys
    try:
    import pygtk
    pygtk.require(“2.0″)
    except:
    pass
    try:
    import gtk
    except:
    sys.exit(1)

    class HelloWorldGTK:
    “””This is a Hello World GTK application”””

    def __init__(self):

    #Set the Glade file
    self.builder = gtk.Builder()
    self.builder.add_from_file(“pyhelloworld.glade”)

    #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)

    dic = {
    “on_btnHelloWorld_clicked” : self.btnHelloWorld_clicked,
    “on_MainWindow_destroy” : self.quit
    }

    self.builder.connect_signals( dic )

    def btnHelloWorld_clicked(self, widget):
    #print “Hello World!”
    #self.builder.get_object(“label1″)
    #lbl = “label1″
    #lbl.set_text(“Hello World!”)
    self.builder.get_object(“label1″).set_text(“Hello World!”)

    def quit(self, widget):
    sys.exit(0)

    if __name__ == “__main__”:
    HelloWorldGTK = HelloWorldGTK()
    gtk.main()

  160. Mark Tiddens
    Says:

    Note that the above coce will not run if you cut and paste it because, unfortunately, this forum doesn’t seem to provide an option to insert code without it losing it’s indentations, which of course Python must have.

    I’m going try to use the code prefixes used on other forum comments to see if the indents are preserved:

    ::HLIGHT_BLOCK_1::

  161. Mark Tiddens
    Says:

    Nope – “::HLIGHT_BLOCK_1::” doesn’t work. Can someone advise how to post code here?

  162. KP
    Says:

    Very good tutorial. I followed the instructions step by step, the ran the python code. Nothing HAPPENED–the Hello World window did not appear…I am using Windows 7. Is that an issue? What code modifications are needed? See code below: I change sys to os–sys kept throwing up:

    Traceback (most recent call last):
    File “C:\…(path)
    sys.exit(1)
    SystemExit: 1

  163. jelly roll kraemer
    Says:

    Heya i am for the first time here. I came across this
    board and I in finding It truly helpful & it helped me out much.
    I am hoping to offer something back and help others
    like you aided me.

  164. Landscaping Houston TXm Landscaping The Woodlands TX
    Says:

    Hey there, I think your blog might be having browser
    compatibility issues. When I look at your blog site in Firefox, it looks fine but when opening in
    Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that,
    very good blog!

  165. Jerry
    Says:

    Hello, I have been struggling with using python and Glade to develop a few simple GUI based apps for my Ubuntu 12.04 based PC.
    It seems difficult to locate tutorial books and documentation to download and experiment with.

    Can anyone offer suggestions for a tutorial PDF that goes into the details of using the GTK+ imports. I get stumped when I try to figure out what the different attributes and methods that can be used with the imports associated with using Glade.

    I did take a look at Tkinter as it is included with the Python install (python 2.7.3) and as mentioned elsewhere, iy is not ‘pretty’.

    I have done some VB.NET on a XP PRO PC, so some of the concepts make sense and some do not.

    Without the ability to generate GUI programs the use of Python is somewhat limited.

    Most of the tutorials from the Glade website(s) seems to center on using C/C++ . I have a good amount of C experience , but that is using micro controllers , so not a big amount of help there. I really want to use Python for Linux (Ubuntu) work and not have to use C.

    Also, I really don’t want to have to use XML. From what I read, Glade takes care of that for you(?).

    So, I am hoping that I can get some good suggestions from here.

    I also don’t understand the difference from using PyGTK and/or Glade. Glade seems to offer the better of the worlds.

    Thanks for your postings and I will continue to keep digging.

    Best Regards to all.

  166. how to get a google plus account
    Says:

    Hi to every , because I am in fact keen of reading this blog’s post to be updated on
    a regular basis. It includes pleasant information.

  167. YOLO
    Says:

    If you desire to obtain a great deal from this article then you have to apply these methods to your won weblog.

  168. Jerry
    Says:

    I have been looking for a decent example of using Glade. I will come back here again and take another look at it. I am currently using wxpython at the beginner level. I am just doing this stuff as a hobby. Glad may be easier to use, not sure.

Leave a Reply

 

Popular Posts