FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 22.1 | Next Entry >>

22.1. How do I use PyGTK and glade together (using libglade)?

For a more in depth answer see the Glade articles at [www.pygtk.org]

Basically, the steps involved are:

1. Create your interface with glade, and save the XML file (say, foo.glade).

2. Implement the relevant code using gtk.glade:

  import gtk.glade
  # instantiate XML object
  tree = gtk.glade.XML("foo.glade")
  # get references to individual widgets
  w1 = tree.get_widget("window1")
  e1 = tree.get_widget("entry1")
Some explaining is due. First, by instantiating an gtk.glade.XML object, you are actually parsing the glade file in runtime. The XML instance abstracts the glade widget tree, which is why it's often named "tree" or "wTree" in examples.

It's important to understand that by creating an XML instance you are in fact *generating the UI*, and all widgets will be created in this step. To deal with visibility issues, see FAQ 22.6.

The most important method in the XML instance is get_widget(), which returns widgets defined in your glade file by name. Glade assigns names by default, and the pattern is usually <widgetname><number>; in the example above we are using the default widget names for a GtkWindow and a GtkEntry. You are advised to change these names to something that makes sense for your application to avoid going insane performing code maintenance.

If you'd like to deal with signals defined in the gladefile, take a look at FAQ 22.4.

Keep in mind that gtk.glade automatically caches XML trees. So don't try any complex tricks to reuse XML trees if you have to create the same UI multiple times. The correct thing to do is simply to instantiate the XML multiple times with the same parameters.

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org