Programming threads always had its difficulties. But when you are combining threads with gui programming things may get really complicated very fast. Especially if you have to consider specific details of the toolbox and the OS you are using. These pages are an attempt to help people using PyGTK to get on their way. A number of demos are available that will be used to explain various aspects. Some experience with PyGTK is required since we expect readers to know most of the pygtk calls and objects used. All demos implement the same functionallity. When you start up the application the following frame appears.
Every line represents one thread. The model is somewhat based on a stop watch. Pressing Start/Stop will run or interrupt the thread. Pressing Modus will change what information gets displayed or reset the thread. Clicking near the colored bars will have the same effect as pressing all Start/Stop buttons at the same time.
The program consists mainly of two parts. Firts we have the working threads that continuously produce results that are to be shown in the window. The structure of the working thread is as follows.
class Counting (Thread): def __init__(self, Id) def run(self): while ...: Calculate Results Communicate Results def Start_Stop(self,ignore) def Modus(self,ignore): if Running: Change Mode else: Reset Values Communicate Results def Quit(self): Make thread stop
Then we have the gtk thread. This thread is mainly concerned with the user interaction. We have a frame with buttons and a canvas. The frame has a delete handler. The buttons are connected to the respective methods of the working threads. We also have the canvas which has an expose handler and a button press handler. These all are pretty standard stuff with gtk programs so will not be further explained here. Finaly the canvas has an Adjust method. This method takes the necessary parameters to adjust the canvas to the latest results of a thread. However a thread communicates its result, it will be this method that shows them on the canvas.
To work with threads in pygtk you have to call gtk.gdk.threads_init() before you call gtk.main(). Some suggest you also should put gtk.gdk.threads_enter() and gtk.gdk.threads_leave() around gtk.main(). However doing so never made a difference for me. But if you are experiencing trouble, it always is something to try out.