I have just learned a few more tricks on how to best work with GTK and Python. First, let me start at the beginning. After you create a Glade file (If you don't know what Glade is, read this), the next step is to create the Python code to load the Glade file (i.e. turn the XML into actual widgets on the screen), and hook up all the signals to actual Python methods. Well, if you're like me, you don't know how many parameters are needed for each signal handler, and soon you find yourself looking for examples (or just guessing) on how to hook up various signals (such as a button click, treeview drag_begin, window destroy, etc...). This can become a very time consuming and frustrating process, especially when you are just learning Python & GTK.
Trick #1: Using Synaptic Package Manager (or equivalent), go get the tepache package. This package gives you a command line way of generating the Python code needed to load a Glade file into a class, auto-connect all the signals, and it even stubs out all the signal handler methods. If that wasn't enough, it even helps setup language translations for your Glade file.
To use the tepache command, use the following syntax in the terminal window: tepache YourFile.Glade
After you run this command, it will generate a .py file, named YourFile.py. Here is the output from the tepache command using one of my more complex Glade files:
Trick #2: There is a library that comes with pyGtk called SimpleGladeApp, which is going to save you a ton of time. It is used quite heavily in the tepache output (as you can see from my example). What does this library do, you ask?
Let me break it down for you:
- It loads a Glade XML file and returns an object for your form. It reminds me very much of a form object from the Windows world (i.e. Visual Basic.NET, C# Windows Application, etc...).
- On this new form object, it has a reference to every single widget on your form. For example: self.myTree, self.btnToolBar1, self.Canvas1.
- It adds a show() and hide() method for every widget.
- It adds a grab_focus() method for every widget.
- It adds a run() and quit() for your form (which simply calls the main_loop() gtk methods.
- It auto-connects all the signal handlers you have defined (of that tepache defined) to the signals defined in the Glade file.
- It translates all the text in the Glade file (if you have the appropriate translation files in your project).
I hope this blog entry is helpful to some of you. It's going to save me a ton of time trying to setup my GUI and hook up all the signals. Good luck!