1. PyGTK recipes
This page lists code snippets for PyGTK that I (as every-once-in-a-while PyGTK user) usually have to search for, or that describe things that are not intuitively to find and that should be documented hence.
For now, this is quite unorganized (probably until there are enough entries to warrant better organization).
The recipes are targeted at
Glade-based apps
- somewhat experienced developers (with understanding of programming and basic understanding of Python)
Feel free to add your own recipes.
1.1. Basic .glade file loading
Assuming you have a glade file with name myGui.glade, you can load it like this:
If you have added a handler for the GtkWidget.delete-event in Glade (lets say with a handler named "on_mywindow_delete"), you should add this to your MyGUI class to handle the "close window" event (in this example, by quitting the app):
1.2. Creating a simple list box from a gtk.TreeView
How to create a very simple list box (based on a GtkTreeView control in the glade file):
1 self.treeview = self.tree.get_widget("myTreeView")
2 liststore = gtk.ListStore(str) # create a list store with just one column (which holds a string)
3 self.treeview.set_model(liststore)
4
5 cr = gtk.CellRendererText()
6 tc = gtk.TreeViewColumn("TheTitle", cr, text=0)
7 self.treeview.append_column(tc)
(TODO: there must be an easier way to do this! But how??)
To sort the listbox entries alphabetically, add this as well:
1 liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
... alternatively, you can make a specific column sortable for the user ("tc" is a TreeViewColumn which was created before; 0 is the index of the liststore column which belongs to the TreeViewColumn):
1 tc.set_sort_column_id(0)
If you want to have the column sorted right from the beginning, simulate a "click" on the column header like this:
1 tc.emit("clicked")
(note that for this to work, you must have already added the column to a treeview, with append_column).
Add new entries to the list box like this:
1 self.treeview.get_model().append(["The Entry Text"])
To react on selection changes you have to handle the "changed" event.
Register a selection change handler like this (if you don't want to specify the handler directly in Glade):
1 self.treeview.connect("changed", self.on_myTreeView_changed)
... and then implement the handler like this:
1.3. Using a gtk.TextView control
If you have added a GtkTextView in Glade (lets say with name "myTextView"), do this after loading the .glade file:
To append a new line:
1 self.textBuffer.insert_at_cursor(line, len(line))
To change the whole text at once:
1 self.textBuffer.set_text(myNewText)
1.4. Changing TextView font
Instead of the hardcoded name you can get the font name also with
1 fontName = fontDialog.get_font_name()
(TODO: add a "correct way" for setting a TextView to user-preferred monospace font)