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

Popularity: 92%

Related Posts

  • Japanese translation!
  • Tutorial Index
  • Novemeber
  • Just a quick post before I leave
  • PyLan a GTD todo application written in python and PyGTK - part four context menus!

  • del.icio.us del.icio.us blinklist

    124 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Says:

      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!

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

      Hi Koorghan,

      Thanks I’m glad that you liked the tutorial!

    67. Leo Says:

      Very good tutorial!

    68. 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 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):
        printHello 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 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 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 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 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 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 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 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 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 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 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 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 Says:

      Hi Shrikrishna,

      Thanks for the kind words!

    106. 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 ano