Building an Application with PyGTK and Glade


After working with PyGTK and Glade for my first tutorial, I decided to write another more complex tutorial but I couldn’t think of a topic (Note: If you have any suggestions for any tutorials or posts I’d love to hear them) so I decided to work on creating a simple application and hopefully useful topics would arise from there.

The idea I came up with (which will hopefully be simple) is to create a program that will allow me to keep track of the different types of wine that I drink and how much I like them. It’s something I’ve wanted to write for a while so I thought it would be good to combine learning PyGTK and doing it.

I’m going to call the project PyWine. The full source and Glade file for this tutorial can be found here

The first thing to do is start a new Glade project in the projects directory called PyWine. Create a new Window, call it “mainWindow,” and set the title to be “PyWine”. Then add a handler to the destroy signal just like in the first tutorial.

Next I add a Vertical Box to the Window with 4 rows, (from top to bottom) one row for a Menu bar, one row for a Toolbar, one row for a Tree or List View, and the final row for a Status Bar. Name the Tree View “wineView”

Python Glade

The Tree or List View that we added to the window will be used to display the wines information to the user. So the first thing that we are going to want to do is allow the user to add a wine to the dialog. To do this we are going to use a menu command and a Toolbar button.

The first thing to add is a toolbar button. To do this simply select the toolbar button in the Pallet and click on the toolbar that we added to the window. This should add a strange looking button to your toolbar. Now we are going to edit the toolbar buttons properties on the Widget tab. We’ll set its name to be “tbAddWine”, its label to be “Add Wine”, and it’s icon to be the stock add icon.

Note: A user Thomas Says: “With glade 3 the toolbar buttons aren’t available in the palette. You have to add buttons to the toolbar by right clicking in the toolbar, selecting add and then add the toolbar button.”

Python Glade

Now we’ll add a handler for the tbAddWine button’s click event but this time instead of calling it the default “on_tbAddWine_clicked” we’ll call the handler “on_AddWine”.

Adding to the Menu Bar

Now we are going to work on the menu, since we want people to be able to add items from the taskbar button or from the Menu Bar. So click on the Menu Bar in the window and go to the Widget tab in the properties window. Then click on the “Edit Menus…” button to edit the Menu Bar.

Now click the Add button to add a new top level menu item, and sets it’s label to be “_Add”. Then select the Add item in the menu list and click the “Add Child” button, this will create a sub-menu within the Add menu. Set the new items label to be “_Wine” and set it’s handler to be: “on_AddWine”.

You’ll notice that the handled for the Add toolbar button clicked event and the Add | Wine menu activation are the same. This is because both of those two widgets will be performing the exact same task, adding a wine to our wine list.

Python Glade Menu Editor

So what’s going to happen when the user clicks on the Add Wine button or selects Add | Wine from the menu, is a dialog will pop up allowing them to enter in details about the wine. If they choose the “Ok” button to end the dialog the wine information that they entered will be added to the ListView.

Creating a dialog

So the next thing that we need to do is create the dialog that the user will use to add a new wine. For this example we’ll keep things pretty simple and let the user enter the wine name, the winery, the year it was bottled, and the grape variety.

So to create a new dialog simply click the Dialog button on the Glade Palette window. This should bring up the New Dialog window, in it choose the “Standard button layout” option with Cancel and Ok as the buttons. Now set the dialogs name to be “wineDlg” and it’s window title to be “Add Wine”.

Next we will use a table to lay things out in our wineDlg, add the table to your dialog (in the normal way that you add widgets to a window) and set the number or rows to be 4 and the number of columns to be 2. Then we’ll fill in the spaces of the table with Label and Text Entry widgets until the dialog looks something like this:

Python Glade Menu Editor

I added three pixels of spacing between the rows of the table, this setting can be found on the widget tab of the table’s properties. If you are having trouble selecting the table you can select View | Show Widget Tree from the menu in the main Glade window and select the table in the widget tree. Or you can hold down the SHIFT key and left click on the widgets in the table, this will allow you to cycle through the widgets on the dialog.

Now we are going to have to name all of the edit fields on the dialog, name then: enWine, enWinery, enGrape, and enYear.

The Python Code

Now we are going to take that code and get it working, we’ll call our python file pywine.py and create it in our /projects/PyWine directory (the same directory where we created our glade files). The following is the basic code that we will use (most of it taken form the first PyGTk/Glade tutorial):

#!/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 pyWine:
"""This is the PyWine application"""

def __init__(self):

#Set the Glade file
self.gladefile = "pywine.glade"
self.wTree = gtk.glade.XML(self.gladefile, "mainWindow")

#Create our dictionay and connect it
dic = {"on_mainWindow_destroy" : gtk.main_quit
, "on_AddWine" : self.OnAddWine}
self.wTree.signal_autoconnect(dic)

def OnAddWine(self, widget):
"""Called when the use wants to add a wine"""

print "OnAddWine"

if __name__ == "__main__":
wine = pyWine()
gtk.main()

There are a few new additions to this code, one is the handler for the on_AddWine signal, if you run this code you’ll notice that “OnAddWine” will be printed out when you click the Add Wine button and when you select Add | Wine from the menu. The other new addition to the code is that we pass the name of the main window to gtk.glade.XML. This lets us load only that window and it’s children.

The next thing that we are going to create is a Wine class that we will use to store the wines information:

class Wine:
"""This class represents all the wine information"""

def __init__(self, wine="", winery="", grape="", year=""):

self.wine = wine
self.winery = winery
self.grape = grape
self.year = year

Pretty simple, the next thing that we are going to create is a class that we’ll use for our wineDlg dialog, we’ll call it wineDialog:

class wineDialog:
"""This class is used to show wineDlg"""

def __init__(self, wine="", winery="", grape="", year=""):

#setup the glade file
self.gladefile = "pywine.glade"
#setup the wine that we will return
self.wine = Wine(wine,winery,grape,year)

The next thing we need to do is add a function to our wineDialog class that will load the wineDialog widget from the glade file and show it. We will also want this function to return the result of the dialog, this will be a gtk.RESPONSE, you can read more about these at the PyGTK website.

Here is the run function:

def run(self):
"""This function will show the wineDlg"""

#load the dialog from the glade file
self.wTree = gtk.glade.XML(self.gladefile, "wineDlg")
#Get the actual dialog widget
self.dlg = self.wTree.get_widget("wineDlg")
#Get all of the Entry Widgets and set their text
self.enWine = self.wTree.get_widget("enWine")
self.enWine.set_text(self.wine.wine)
self.enWinery = self.wTree.get_widget("enWinery")
self.enWinery.set_text(self.wine.winery)
self.enGrape = self.wTree.get_widget("enGrape")
self.enGrape.set_text(self.wine.grape)
self.enYear = self.wTree.get_widget("enYear")
self.enYear.set_text(self.wine.year)

#run the dialog and store the response
self.result = self.dlg.run()
#get the value of the entry fields
self.wine.wine = self.enWine.get_text()
self.wine.winery = self.enWinery.get_text()
self.wine.grape = self.enGrape.get_text()
self.wine.year = self.enYear.get_text()

#we are done with the dialog, destroy it
self.dlg.destroy()

#return the result and the wine
return self.result,self.wine

You’ll notice that we load the dialog form the glade file in the same way that we load the main window. We call gtk.glade.XML() and pass it the name of the widget that we want to load. This will automatically show the Dialog (in the same way that it does our main window) but that’s not good enough for us, we want the run function to wait until the user has exited the dialog before we return to the caller. To do that we call get the dialog widget from the widget tree (self.dlg = self.wTree.get_widget("wineDlg")) and we call the GTkDialogs run function. I’ll let the PyGTk documentation describe what this function does:

The run() method blocks in a recursive main loop until the dialog either emits the “response” signal, or is destroyed. If the dialog is destroyed, the run() method returns gtk.RESPONSE_NONE; otherwise, it returns the response ID from the “response” signal emission. Before entering the recursive main loop, the run() method calls the gtk.Widget.show() on the dialog for you. Note that you still need to show any children of the dialog yourself.

During the run() method, the default behavior of “delete_event” is disabled; if the dialog receives a “delete_event”, it will not be destroyed as windows usually are, and the run() method will return gtk.RESPONSE_DELETE_EVENT. Also, during the run() method the dialog will be modal. You can force the run() method to return at any time by calling response() to emit the “response” signal. Destroying the dialog during the run() method is a very bad idea, because your post-run code won’t know whether the dialog was destroyed or not.

After the run() method returns, you are responsible for hiding or destroying the dialog as needed.

The Ok button will return gtk.RESPONSE_OK and the Cancel button will return gtk.RESPONSE_CANCEL, for the most part we only care about the wine that is returned by this dialog if the user clicks the Ok button.

You can also see that we get the GTKEntry widgets from the dialog in order to get and set their text. All-in-all this function is pretty simple.

Tree Views and List Stores

Now that we have the wine the the user wanted to add to the list we need actually add it to the gtk.TreeView.

The main feature of GTKTreeViews is that they display their data in whatever way their model tells them to. They can use a gkt.ListStore, gtk.TreeStore, gtk.TreeModelSort, or a gtk.GenericTreeModel. For this example we’re going to be using a gtk.ListStore.

The relationships between Tree View’s and Models is a bit complicated but once you start using it you’ll begin to understand why they did it this way. In a very basic form the Model represents the Data, and the Tree View is simply a way to display the data. So you can have multiple views display the same data (model) in totally different ways. From the GTk+ reference manual:

To create a tree or list in GTK+, use the GtkTreeModel interface in conjunction with the GtkTreeView widget. This widget is designed around a Model/View/Controller design and consists of four major parts:
The tree view widget (GtkTreeView)
The view column (GtkTreeViewColumn)
The cell renderers (GtkCellRenderer etc.)
The model interface (GtkTreeModel)

The View is composed of the first three objects, while the last is the Model. One of the prime benefits of the MVC design is that multiple views can be created of a single model. For example, a model mapping the file system could be created for a file manager. Many views could be created to display various parts of the file system, but only one copy need be kept in memory.

The first thing we need to do is add some code to the __init__ function of the pyWine class right after we auto-connect the dictionary to the widget tree:

#Here are some variables that can be reused later
self.cWine = 0
self.cWinery = 1
self.cGrape = 2
self.cYear = 3

self.sWine = "Wine"
self.sWinery = "Winery"
self.sGrape = "Grape"
self.sYear = "Year"

#Get the treeView from the widget Tree
self.wineView = self.wTree.get_widget("wineView")
#Add all of the List Columns to the wineView
self.AddWineListColumn(self.sWine, self.cWine)
self.AddWineListColumn(self.sWinery, self.cWinery)
self.AddWineListColumn(self.sGrape, self.cGrape)
self.AddWineListColumn(self.sYear, self.cYear)

This code is pretty straight forward, first we create a few variables that act as defines for us (so that we can easily change things around later) then we get our gtk.TreeView from the widget tree. After that we call a new function to add the columns that we need in the list. AddWineListColumn just a quick function that stops us from having to replicate the column create code each time:

def AddWineListColumn(self, title, columnId):
"""This function adds a column to the list view.
First it create the gtk.TreeViewColumn and then set
some needed properties"""

column = gtk.TreeViewColumn(title, gtk.CellRendererText()
, text=columnId)
column.set_resizable(True)
column.set_sort_column_id(columnId)
self.wineView.append_column(column)

This code is a bit more complicated, first we create a new gtk.TreeViewColumn that uses a gtk.CellRendererText as it’s gtk.CellRenderer. Here is a bit more general information from the GTK+ reference manual:

Once the GtkTreeView widget has a model, it will need to know how to display the model. It does this with columns and cell renderers.

Cell renderers are used to draw the data in the tree model in a way. There are a number of cell renderers that come with GTK+ 2.x, including the GtkCellRendererText, GtkCellRendererPixbuf and the GtkCellRendererToggle. It is relatively easy to write a custom renderer.

A GtkTreeViewColumn is the object that GtkTreeView uses to organize the vertical columns in the tree view. It needs to know the name of the column to label for the user, what type of cell renderer to use, and which piece of data to retrieve from the model for a given row.

So basically what we are doing is creating a column with a specific title, specifying that it will use the gtk.CellRendererText (to display simply text), and telling it which item in the model it is attached to. The we make it resizable and allow the user to sort the list by clicking on a columns header. After that all we do is add the column to the View.

Now that that’s done we need to create our Model, we’ll do this back in the __init__ function of the pyWine class:

#Create the listStore Model to use with the wineView
self.wineList = gtk.ListStore(str, str, str, str)
#Attatch the model to the treeView
self.wineView.set_model(self.wineList)

Basically we simply create a gtk.ListStore and tell it that it will have four items, all of which will be strings. Then we attach the model to the view and that’s all the initialization that we need to do for out gtk.TreeView.

Putting it all Together

The last thing that we need to do is write the OnAddWine function (called from the menu or the toolbar button) in the pyWine class. It’s a pretty simple function:

def OnAddWine(self, widget):
"""Called when the use wants to add a wine"""
#Create the dialog, show it, and store the results
wineDlg = wineDialog();
result,newWine = wineDlg.run()

if (result == gtk.RESPONSE_OK):
"""The user clicked Ok, so let's add this
wine to the wine list"""
self.wineList.append(newWine.getList())

So we create an instance of our wineDialog and then we run it storing the result and the wine information that the user entered. Then we check to see if the result was gtk.RESPONSE_OK (the user clicked on the Ok button) and if it is we then add the wine information to our gtk.ListStore which will automatically be displayed in our gtk.TreeView since the two are connected.

We make use of the simple getList function in our wine class to make this slightly easier to read:

def getList(self):
"""This function returns a list made up of the
wine information.  It is used to add a wine to the
wineList easily"""
return [self.wine, self.winery, self.grape, self.year]

Python PyGTK PyWine Glade

That’s about it for this sample application, granted it doesn’t save any of the information or anything like that yet, but it does outline some of the initial steps to creating a full pyGTk application.

The full source and Glade file can be found here you can also browse the full source below:

#!/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 pyWine:
"""This is an PyWine application"""

def __init__(self):

#Set the Glade file
self.gladefile = "pywine.glade"
self.wTree = gtk.glade.XML(self.gladefile, "mainWindow")

#Create our dictionay and connect it
dic = {"on_mainWindow_destroy" : gtk.main_quit
, "on_AddWine" : self.OnAddWine}
self.wTree.signal_autoconnect(dic)

#Here are some variables that can be reused later
self.cWine = 0
self.cWinery = 1
self.cGrape = 2
self.cYear = 3

self.sWine = "Wine"
self.sWinery = "Winery"
self.sGrape = "Grape"
self.sYear = "Year"

#Get the treeView from the widget Tree
self.wineView = self.wTree.get_widget("wineView")
#Add all of the List Columns to the wineView
self.AddWineListColumn(self.sWine, self.cWine)
self.AddWineListColumn(self.sWinery, self.cWinery)
self.AddWineListColumn(self.sGrape, self.cGrape)
self.AddWineListColumn(self.sYear, self.cYear)

#Create the listStore Model to use with the wineView
self.wineList = gtk.ListStore(str, str, str, str)
#Attache the model to the treeView
self.wineView.set_model(self.wineList)

def AddWineListColumn(self, title, columnId):
"""This function adds a column to the list view.
First it create the gtk.TreeViewColumn and then set
some needed properties"""

column = gtk.TreeViewColumn(title, gtk.CellRendererText()
, text=columnId)
column.set_resizable(True)
column.set_sort_column_id(columnId)
self.wineView.append_column(column)

def OnAddWine(self, widget):
"""Called when the use wants to add a wine"""
#Cteate the dialog, show it, and store the results
wineDlg = wineDialog();
result,newWine = wineDlg.run()

if (result == gtk.RESPONSE_OK):
"""The user clicked Ok, so let's add this
wine to the wine list"""
self.wineList.append(newWine.getList())

class wineDialog:
"""This class is used to show wineDlg"""

def __init__(self, wine="", winery="", grape="", year=""):

#setup the glade file
self.gladefile = "pywine.glade"
#setup the wine that we will return
self.wine = Wine(wine,winery,grape,year)

def run(self):
"""This function will show the wineDlg"""

#load the dialog from the glade file
self.wTree = gtk.glade.XML(self.gladefile, "wineDlg")
#Get the actual dialog widget
self.dlg = self.wTree.get_widget("wineDlg")
#Get all of the Entry Widgets and set their text
self.enWine = self.wTree.get_widget("enWine")
self.enWine.set_text(self.wine.wine)
self.enWinery = self.wTree.get_widget("enWinery")
self.enWinery.set_text(self.wine.winery)
self.enGrape = self.wTree.get_widget("enGrape")
self.enGrape.set_text(self.wine.grape)
self.enYear = self.wTree.get_widget("enYear")
self.enYear.set_text(self.wine.year)

#run the dialog and store the response
self.result = self.dlg.run()
#get the value of the entry fields
self.wine.wine = self.enWine.get_text()
self.wine.winery = self.enWinery.get_text()
self.wine.grape = self.enGrape.get_text()
self.wine.year = self.enYear.get_text()

#we are done with the dialog, destory it
self.dlg.destroy()

#return the result and the wine
return self.result,self.wine

class Wine:
"""This class represents all the wine information"""

def __init__(self, wine="", winery="", grape="", year=""):

self.wine = wine
self.winery = winery
self.grape = grape
self.year = year

def getList(self):
"""This function returns a list made up of the
wine information.  It is used to add a wine to the
wineList easily"""
return [self.wine, self.winery, self.grape, self.year]

if __name__ == "__main__":
wine = pyWine()
gtk.main()

The next installment of the PyWine tutorial: Extending our PyGTK Application is available.

selsine

del.icio.us del.icio.us

101 Responses to “Building an Application with PyGTK and Glade”

  1. Jesus Rodriguez
    Says:

    Thank you very much friend!!!!, is a VERY good tutorial, i want to see more tutorials from you!

    Thanks :)

  2. Michael
    Says:

    Very nice tutorial, thanks.

  3. selsine

    selsine
    Says:

    Hey Guys, thanks for the kind words I’m glad that you both liked it.

  4. Nazgob
    Says:

    Again good job!

  5. Josh
    Says:

    Thanks, your tutorials are very valuble!

  6. learning python » Blog Archive » Just a quick post before I leave
    Says:

    [...] I’ve been meaning to do this for a while but simply couldn’t find the time up until right before I leave on my trip. Here is a quick screenshot of my last tutorial running on Windows: [...]

  7. J-N
    Says:

    Nice tutorial, although I think I might’ve missed a step? I did everything but when I add a new wine, fill the fields in the dialog, and click the OK button, nothing happens! I tried replacing my python code with the one from your source but still, nothing is happening… Do I have to add handlers in the dialog (wineDlg)? Is there something I’m missing?

  8. J Porter
    Says:

    To J-N up above.

    I had the same problem.

    Didn’t see it mentioned in the tutorial but when you are making the OK and Cancel buttons for your addWine dialog, select one of the buttons (make sure its the actual button). Under the widget tab you’ll see an area labeled “Response ID”. For the Ok button select GTK_RESPONSE_OK and for the Cancel button select GTK_RESPONSE_CANCEL. Save it. Re-run your script.

    BTW, just because I didn’t see this mentioned it could probably still be in the tutorial. :)

  9. selsine

    selsine
    Says:

    Hi J-N and J Porter,

    J Porter is right you need to have your buttons returning response Id’s. But if you create your dialog in the method I outlined above (selecting a standard button layout with Cancel and OK) Glade should set those response IDs automatically.

    If it is not, this may be a result of different versions of Glade, let me know and I will include a note in this tutorial.

    If anyone runs into any problems with these tutorials please let me know, I will either try to help you or fix the tutorial if there is an error.

  10. logiX87
    Says:

    Hi,

    thanks for this simple, but very helpful tutorial.

  11. XeeD
    Says:

    Thank you very much for this great tutorial. It helped me to understand how GTK works and how to use it.

  12. Jeff
    Says:

    Hi,
    I had this working on windows honest. But now it doesn’t, I think I removed some program necessary to make it run.
    I have checked what I thin and re-installed but seem to get an error telling me GTK isn’t loaded right although I feel it is installed ok.

    Is there a definitive list of what needs installed to run/develop this , eg Python, GTK, PyGTK, Glade etc. I’m finding this hard to achieve.

    Thanks
    Jeff

  13. Chris Webber
    Says:

    Actually, there’s a mistake in this… it shouldn’t be “destroy event”, but rather “delete event” in this tutorial. “Destroy event” for the main window. Otherwise it won’t quit right.

  14. selsine

    selsine
    Says:

    Jeff – Checkout this FAQ it should help you get everything working on Win32 – PyGTK FAQ

    Chris – Are you sure it’s supposed to be the “delete event”? It seems to close down fine for me, and the destroy event to be what the PyGTK Tutorial recommends. I could be wrong though, Perhaps you could explain a bit more?

  15. Daniele Medri
    Says:

    Nice tutorial.

    Python and PyGtk rules and we need more article like this to dominate the world.

  16. luks;
    Says:

    Excellent Tutorial!
    Your blog is helping a lot on mine python journey
    thanks!

  17. ves
    Says:

    Really nice tutorial, cheers for writing it.

  18. OneSeventeen
    Says:

    for me, I had to connect the “destroy” event to gtk.main_quit for the exit button to work, similar to your previous tutorial.
    I also changed the handler for the “quit” menu item to “on_mainWindow_destroy”, so the dictionary we connected did something.

    The only other thing I did differently was pointed everything to self.quitApp instead of gtk.main_quit, so I could have a function handle all the exit stuff (such as printing out “So long and thanks for all the wine”)

    Anyway, this was an AWESOME tutorial! This the second time I have ever touched python (the first was in your previous tutorial), and a lot of the stuff actually make sense! Keep it up!

  19. selsine

    selsine
    Says:

    Hey Guys thanks for all of the kind words and the helpful tips! I really appreciate it.

  20. Chris Webber
    Says:

    selsine: I guess you were right.. my mistake was that I was connecting destroy_event instead of destroy :)

    Thanks for this awesome tutorial. It’s helped me 1000x. I hope you continue to make such useful tutorials.

  21. selsine

    selsine
    Says:

    Hey Chris, actually when I started working on my current tutorial (not up yet, hopefully soon) I actually realized that this was the problem. I think I’m going to try to make that more obvious in this tutorial and in my future ones. I’m glad you liked the tutorials!

  22. Kevin Horton
    Says:

    I’m just learning GTK python, and these two tutorials have been extremely helpful. Keep up the great work.

    Thank you very much.

    Peace.

  23. learning python » Blog Archive » WordPy offline blogging tool
    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. [...]

  24. S. Tanabe
    Says:

    Some typos:

    (1)
    >it’s name to be “tbAddWine”, it’s label to be “Add Wine”, and it’s icon
    (several others)

    it’s -> its

    (2)
    >this will create a sub-menu withing the Add menu.

    withing -> within

    (3)
    >hold down the SIFT key

    SIFT -> SHIFT

    (4)
    >”””This is an Hello World GTK application”””

    Hello World GTK -> PyWine

    (5)
    >[code language=”python”]
    >def AddWineListColumn(self, title, columnId):
    >“”"This function adds a column to the list view.
    ...........
    >self.wineView.append_column(column)
    >[/code]

    Problem with formatting?

    (6)
    >The main feature if CTKTreeViews is

    CTKTreeViews -> GTKTreeViews

    Japanese translation is almost done:
    http://po3a.blogspot.com/2006/08/pygtk-glade.html

  25. learning python » Blog Archive » Extending our PyGTK Application
    Says:

    [...] In this tutorial we are going to extend our PyWine application to allowing you to edit the items that you have added to the list and save an load the wine lists you create so that you don’t have to keep entering them in all the time. [...]

  26. selsine

    selsine
    Says:

    Thanks for the typo catches Satoshi! Very much appreciated, I have fised them up, let me know if you find any more!

  27. Blog de packo » Python + GTK + Glade
    Says:

    [...] AquĂ­ pongo un enlace de cĂłmo trabajar con este sistema, mĂĄs adelante harĂŠ una guĂ­a completa de esto y ademĂĄs de cĂłmo sacar aplicaciones standalones para Windows con este sistema a travĂŠs de py2exe. building-an-application-with-pygtk-and-glade/ [...]

  28. richard
    Says:

    thank u .. i spent lots and lots of time to learn this pygtk+glade (nearly 1 year).

    this tutorial is a wonderful one.

    thank u once again…

    i must make a note of this site for every learner of pygtk+glade…

    love
    richard

  29. selsine

    selsine
    Says:

    Hey thanks richard!

  30. learning python » Blog Archive » Novemeber
    Says:

    [...] I as mentioned in the past Satoshi Tanabe over at satolog has translated a few of my tutorials over into Japanese, which is very cool. It also turns out that someone over at blog.chinaunix.net has also translated one of my tutorials (Building an application with PyGTK and Glade) into Chinese, again very cool! Thanks a lot for the translations guys. [...]

  31. learning python » Blog Archive » Translating your Python/PyGTK application
    Says:

    [...] Building an Application with PyGTK and Glade [...]

  32. Masuran.org » Blog Archive » Python and Glade tutorial
    Says:

    [...] I was exploring the PyGTK.org website in my search for a new development platform when I stumbled upon this wonderful tutorial. Building an application with PyGTK and Glade is a very extensive tutorial on using PyGTK and Glade. [...]

  33. Yarod
    Says:

    Great post :) I’ve translated it to French :
    http://daniel.coquette.free.fr/dotclear/index.php/post/2006/12/18/Construire-une-application-avec-PyGTK-et-Glade
    Thanks for the quality of your tutorials.

  34. jonobacon@home » Using Gnonlin with GStreamer and Python
    Says:

    [...] Right, lets dig in and write some code. Once again, I am going to make the assumption that you are familiar with using a Glade GUI (if you are not see this fantastic tutorial. You should also be familiar with the basics of GStreamer and Python – see my own tutorial for a primer on this. [...]

  35. selsine

    selsine
    Says:

    Yarod – Thanks for another great French translation! Very much appreciated.

  36. Aleksander Kamil Modzelewski
    Says:

    Great tutorial.

    On a side note: on glade 3.1.4 the buttons are not created automatically (there is only a GtkHButtonBox with two empty slots), and the response-id on newly created buttons is 0 (and only numeric values are possible). This may be a version quirk or maybe I’m missing something. Entering -5 and -6 as response ids of OK and Cancel works but seems wrong.

  37. selsine

    selsine
    Says:

    Hi Alexsander,

    Sorry but I don’t have Glade3 installed yet, I’m running Debian testing and all of the necessary packages have not made it in just yet.

    In Glade2 when you add buttons to a GTKHButtonBox you can set the Response ID of the button to something like GTK_RESPONSE_OK, but from what you are saying only numbers are possible, which does seem slightly weird.

    Hopefully I will be able to test out Glade3 soon. Does anyone else using Glade3 have any ideas?

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

    [...] Building an Application with PyGTK and Glade [...]

  39. Felix
    Says:

    selsine, I have Glade 3 too, here’s how it worked for me:

    In Glade, set the response ID for the OK button to anything but 0 (the ID should be unique I guess but since you only need to set the response ID for the OK button, set it to 1)

    now, change the if statement from this

    if( result == gtk.RESPONSE_OK ):

    to this

    if( result == 1 ):

    This did the trick for me, hope this helps.

  40. selsine

    selsine
    Says:

    Hey Felix,

    Thanks for the information! Hopefully that will help Glade 3 users in the future!

    I’m hoping that I will get glade3 on my Debian box soon…

  41. links for 2007-03-01 | the law of averages
    Says:

    [...] learning python Âť Blog Archive Âť Building an Application with PyGTK and Glade (tags: pygtk python gnome glade gui) [...]

  42. Nação Livre » Blog Archive » VocÄ‚Åž jÄ‚Ä„ Garimpou hoje?
    Says:

    [...] http://www.learningpython.com/2006/05/30/building-an-application-with-pygtk-and-glade/ [...]

  43. M4ri00sh
    Says:

    YEAH, a good tutorial. Step by step and it’s working :D
    create some more … :)

  44. Las Noyas de Taran
    Says:

    [...] Este artĂ­culo es una traducciÄ‚Å‚n de <a href=”http://www.learningpython.com/2006/05/30/building-an-application-with-pygtk-and-glade/” class=”ingles”>Building an application with PyGTK and Glade</a>, que se puede encontrar en el blog <a class=”ingles” href=”http://www.learningpython.com”>Learning Python</a>, cuyo autor es Mark Mruss, tambiÄ‚Å n conocido como Selsine. A diferencia de Ä‚Å l yo uso Glade 3, y en consecuencia irÄ‚Å is encontrando comentarios mĂ­os sobre las diferencias entre uno y otro, algunas para peor. [...]

  45. Lord Taran
    Says:

    Hi!
    I’ve translated this tutorial to spanish too! I’ll try to translate all the Pygtk tutorials…

  46. selsine

    selsine
    Says:

    Lord Taran!

    That’s great! I’m away for the weekend and I come back to see that you have translated a bunch of my tutorials! Thanks a lot, I know that there have been more then a few Spanish readers of these tutorials so I am sure that your translations will help people.

  47. Thomas
    Says:

    Since I’ve been stuck quite a long time for finding out where the toolbar button comes from in glade3 here another note for glade3 users:
    With glade 3 the toolbar buttons aren’t available in the palette. You have to add buttons to the toolbar by right clicking in the toolbar, selecting add and then add the toolbar button

  48. selsine

    selsine
    Says:

    Hi Thomas,

    Thanks for the information! I’ve added a small note to the tutorial that will hopefully help out Glade 3 users.

  49. caner
    Says:

    very good tutorial thanks again selsine. but i have a problem which i havent been able to solve yet. when i click on the button in the toolbar ive created, the propery editor just becomes disabled and i cant change the button’s properties. i think i must have missed something. i have read through the posts but i caould find an answer. can someone pls help?

  50. selsine

    selsine
    Says:

    Hi Caner,

    What version of Glade are you using? What happens if you add anything else to the toolbar like a toolbar toggle button or a toolbar radiobutton? Are you able to edit their properties?

    What about when you right click on the button? Can you edit the properties via the right click menu?

  51. caner
    Says:

    it was glade 2 which created the problem i mentioned above. now i ve installed glade 3 and fortunately this doesnt have the same problem. but its interesting that i am the only one having this problem with galde 2 :?. however it is solved. i can continue reading your nice tutorials. and if you dont mind i have some advice again :). what do you think about making video tutorials about glade & python. i think it could be fun for both you and us newbie learners. you must have seen , there is a video tutorial about python and tkinter on the internet. although i didn’t like the apeearence and the abilities of tkinter, i’ve watched them all and it was a good practice. but now i see you can make “working” and cool looking things with gtk. i hope you consider my humble idea. thanks again selsine.

  52. selsine

    selsine
    Says:

    Hi Caner,

    Weird, I use galde 2 and I have never had any similar problems, at least the issue is solved in version 3.

    As far as a video, I have thought long and hard about creating videos in the past, and its always been on the “back-burner” of things that I want to do.

    The problem for me is that it takes long enough to write these tutorials (the python code is the short part) that I barely have any time to explore new ideas. That being said I think it would be possible to take some of the early tutorials and turn them into short little videos.

    That’s one more vote for videos.

  53. Jaacib
    Says:

    Hi

    Thanks for a very nice tutorial!

    /Jaacib

  54. Jak
    Says:

    Hello

    First of all, fantastic blog! It’s very helpful and permanently in my bookmarks.

    I’m curious as to what editor you write your python code in? I’ve been looking for something with autocomplete to help me learn the gtk/glade stuff in python but nothing does it! I can’t tell what the properties and methods are of the Gtk objects, makes it difficult for me to learn. I learn by playing =)

    Thank you

  55. selsine

    selsine
    Says:

    Hi Jak,

    Thanks for the kind words!

    I use http://geany.uvena.de/ for my own work, it doesn’t have auto-complete, but it’s nice and light and lets me jump from function to function and class to class.

    There are a few other nice editors but in my experience they are either too slow or too burdensome to use. SPE (Stani’s Python Editor http://pythonide.blogspot.com/) is quite full featured with a nice auto-complete and is being worked on again so you might want to look at that.

  56. dennis
    Says:

    hi, selsine!
    Do you have plan to write some tutorials about pyqt4?

  57. selsine

    selsine
    Says:

    Hi Dennis,

    Yes I am looking into writing a PyQT4 tutorial, I’ve actually started one but I need to get back to it in order to finish it. At the time I was working on it there seemed to be a few bugs that I couldn’t work around, perhaps it’s been taken care of now.

  58. robson
    Says:

    Just wanted to thank you too for the tutorials. I just started to play with Python and the whole GUI stuff is a bit annoying to me. Second time I came here when I had absolutly no clue why something was not working second time I found the solution (although this time in the comments ;), so I felt like I had to show some appreciation.
    Keep up the good work!

  59. selsine

    selsine
    Says:

    Hi Robson,

    Thanks for the kind words, I really appreciate it.

  60. Brynjar HarĂ°arson
    Says:

    I’m having a problem doing this tutorial

    “The first thing to add is a toolbar button. To do this simply select the toolbar button in the Pallet and click on the toolbar that we added to the window. This should add a strange looking button to your toolbar.”

    The problem is that there doesn’t appear to be any toolbar button in the Pallet, I’m using Glade 3.4.0, so I’m wondering why it’s missing or if I’m missing something, if it has been removed from glade what else can I do?

    Here is a screenshot of my glade pallet: http://pythonnoob.files.wordpress.com/2007/09/glade_pallet.png

  61. selsine

    selsine
    Says:

    Hy Brynjar,

    In Glade 3.0 you have to use the Edit… button on the Toolbar’s properties.

    There you can Add new buttons and separators to the toolbar.

  62. Frederik
    Says:

    It’s really somewhat strange that Glade 3 only allow numeric response codes, I didn’t find a good reason for that.

    But if you want to use gtk.RESPONSE in your code, you can indeed use -5 for GTK_RESPONSE_OK and -6 for GTK_RESPONSE_CANCEL, and it doesn’t have to feel wrong, as Aleksander stated. See e.g. http://developer.gimp.org/api/2.0/gtk/GtkDialog.html for a reference how to map gtk.RESPONSEs to numeric values.

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

  64. selsine

    selsine
    Says:

    Hi Frederik, Thanks for the tip!

  65. emanuel
    Says:

    Thanks for the great tutorials!
    They took me just to the point where iam able to further experiment on my own
    and let me imagine how thinks are done in PyGTK.

  66. Jeff
    Says:

    Great tutorial, the most helpful I have found. Unfortunately there are so many differences with glade3 I haven’t got it working.

    The part on the tool bar button editing “choose the “Standard button layout” option with Cancel and Ok as the buttons.” This option is not available. I guess you have to make the OK and Cancel buttons manually.

    Also in the section “Adding to the menu bar” the part where the instructions are “… click the “Add Child” button, this will create a sub-menu within the Add menu. Set the new items label to be “_Wine” and it’s handler to be: “on_AddWine”.” There is no “add child” button that I can find. The whole thing looks different.

    Many other differences and I haven’t been able to make it work.

    Still its a nice demonstration and it gives me great insight into how to make things work with glade and python.

  67. Jeff
    Says:

    Ok, got it working. With Glade3 after you create a new parent in the menu, you can create a child by right-clicking on the parent. There is no “add child” button but when you right click you can add the child. There are several other differences but if you just tinker with it you;ll find the options you need.

  68. selsine

    selsine
    Says:

    Hi Jeff,

    Thanks for the information, I’ll have to update this tutorial very soon to take into account Glade3. There seem to be a lot of differences between the versions. Some I like, and some I find confusing since I was so familiar with Glade2.

  69. Xtecuan! Ufo
    Says:

    Thanks for the info , I appreciated that!!!!

  70. tasos
    Says:

    Hi!! The link with the full source code is dead.
    Keep up the good work! ;)
    Cheers

  71. selsine

    selsine
    Says:

    Hi tasos,

    Thanks for the information. I have updated the links and they appear to be working now.

  72. Nico
    Says:

    Nice tutorial!

    but i keep getting the error enWine doesnt have the set_text attribute

    ” File “pywine.py”, line 68, in OnAddWine
    result,newWine = wineDlg.run()
    File “pywine.py”, line 98, in run
    self.enWine.set_text(self.wine.wine)
    AttributeError: ‘NoneType’ object has no attribute ‘set_text’

    im using glade 3.4.5, ive tried downloading your python file and get the same error. however if i also use your glade file it runs fine, so im thinking it must be the glade file.

  73. GM
    Says:

    Great set of tutorials! Got me quickly and well into GUI programming! I just took your examples and adapted it for my own as I went rather than simply following yours and its working well! :D

  74. daniel
    Says:

    I have a Problem: If I do exactly the same you did in Glade and take your code it doesnt work. It displays the dialog and everything but I if I add a new Wine nothing is displayed in the TreeView (wineView).

  75. daniel
    Says:

    Im using Glade 3 (sorry for double post)

  76. Karl
    Says:

    @daniel: Check that you have assigned the correct response_ids to your cancel and ok buttons (-6 and -5 respectively). This can be done in glade by selecting the button, then editing the ‘Response ID’ property.

    Great tutorial, very useful to someone like me who is trying to learn python and GTK together.

  77. selsine

    selsine
    Says:

    Hi Nico,

    Take a look at the name of your Wine Edit field in your glade file. I’m guessing that the name in the Python code is different then the name in the Glade file. SO when you get it from the glade file you’re getting None not the Edit.

  78. selsine

    selsine
    Says:

    Hi Daniel and Kary,

    Good point Karl. If nothing is happening Daniel try testing the return code from showing the dialog and seeing what it is.

  79. Kelmer
    Says:

    Man this is not going well. the same problem here, I am using glade 3 and nothing works. Never thought GUI design was so complicated. I think I’ll try Glade 2.

  80. selsine

    selsine
    Says:

    Hi Kelmer,

    Try the suggestion that I put forth to Daniel and Kary. Also Glade 3 works fine, it’s a bit different then Glade3 but I’ve developed a few apps in it and it does work.

  81. Peter
    Says:

    Thank for your tutorial.
    i have tutorial request to create an interface to
    silent install debian package in the background.
    here is the detailed picture.
    http://img232.imageshack.us/my.php?image=help2uf1.jpg

  82. Pablo Torres
    Says:

    I have the weirdest of problems: I cannot see the menu bar! I downloaded your code, ran it, and it wasn’t there on the window. It’s the same when I make my own glade projects – I add a menu bar, but it isn’t there when I ran the app. I’m on glade 2 and 3, using pygtk 2.14.1

    What’s weirdest is that, when on glade 2, I add the menu bar and it isn’t there not even on the glade window. I just see a gray area with no text. The menu bar does appear on glade 3 when designing, but it’s not there when running the app.

    Any suggestions?

  83. Pablo Torres
    Says:

    Nevermind…I have the global-menu app installed…

  84.  Rizwan Mansuri's Blog 
    Says:

    [...] Building an Application with PyGTK and Glade one man’s journey learning Python! added June 1, 2006 [...]

  85. New2pygtk&glade
    Says:

    Hi!

    It took me some time to solve the following problem I had with your tutorial:

    When I used gtk.glade.XML with the .glade files I made using glade3 it wouldn’t work (but gtk.Builder did). Solution: Changing the file format to Libglade in the project’s preferences.

    Maybe that can help s.o. else, too :)

    And thanks for the tutorial, it is really helpful.

  86. deni zakya
    Says:

    nice tutorial, it helps me to finish my final task in my class.

  87. Dennis Gibson Daniels
    Says:

    Any opposition to my posting screencasts of my own feeble efforts to match your successes here?

    If you do object please let me know.

    As well, would you consider doing a screencast of how to connect a standalone python application to a web based server requiring authentication to submit data generated on the python application?

  88. SoftwareExplorer
    Says:

    I am having troubles with my glade file. When I try the one posted here the application works; when I use mine the python terminal seems to do what it should but no window appears. Is there some way I can attach a file?

    Here’s my .glade file:
    http://erikbandersen.com/pywine.glade

  89. Freddie Brandt
    Says:

    Wow. Very nice tutorial. Just what I needed. Thank you!

  90. martin
    Says:

    Perfect tutorial. Thanks for idea

  91. python tut - SoftwareBuzzer.com
    Says:

    [...] Building an Application with PyGTK and Glade one man’s journey learning Python! added June 1, 2006 [...]

  92. Teeter hang ups
    Says:

    Is there a online simulator http://www.treegrid.com/treegrid/www/ by the way the software is fine. If required any special system some one reply me!

  93. Inversion table
    Says:

    I create your post comments while penetrating Google. This Very important in order. Big work. Frequently I do not make posts on blogs, but I have to say that this posting really forced me to do so. Really awesome post. Really fantastic and I will be coming back for more information at your site and revisit it! Thank you.

  94. arun
    Says:

    how to generate .gladep file for me its not coming only .glade file is coming.Should i have to do any settings to get the file.

  95. witchy
    Says:

    Thank you Mark, great tutorial, good explanation. I was comming crazy with tables with glade and python, because I don’t find anything.

    Thanks again, continue making tutorials , you’re great :)

  96. ?????????
    Says:

    Wow, superb blog structure! How long have
    you ever been blogging for? you make running a blog look easy.
    The whole glance of your site is magnificent, as neatly as the content material!

  97. Tony
    Says:

    Thanks for the post. Love it! Long-term fan here Mark!

  98. Immobilien Helmstedt
    Says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog
    that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe
    you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and
    I look forward to your new updates.

  99. soundcloud followers
    Says:

    I for all time emailed this website post page to
    all my friends, as if like to read it after that my links will too.

  100. harga telepon satelit
    Says:

    harga telepon satelit

    learning python » Blog Archive » Building an Application with PyGTK and Glade

  101. google plus authorship
    Says:

    Heya i’m for the first time here. I found this board and I find
    It really useful & it helped me out much.
    I hope to give something back and aid others
    like you helped me.

Leave a Reply

 

Popular Posts