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

<< Previous Entry | FAQ Entry 20.1 | Next Entry >>

20.1. What are the general tips for using threads with PyGTK?

One thread (usually the main thread) should call gtk.threads_init() and gtk.main():

 import gobject


On non-win32 platforms other threads can do window modification, processing, etc. Each of those other threads needs to wrap any GTK+ method calls in a gtk.gdk.threads_enter()/gtk.gdk.threads_leave() pair. Preferably, this should be done in try..finally -- if you miss threads_leave() due to exception, your program will most likely deadlock. If your Python is recent enough, use context manager instead of enter/leave functions:

 with gtk.gdk.lock:
Signal callbacks will be executed in the main thread.

A way to avoid using threads_enter/threads_leave or similar context manager is to call the function from the main thread. A simple way of sending a request to the server is to use gobject.idle_add:

This is recommended for being portable to win32. E.g., if you want to set the text of an entry:

  gobject.idle_add(entry.set_text, 'new text')
But be careful, because it cannot return anything which evaluates to True. If it does, you have to wrap it in a lambda or a separate function (returning True will cause the function being called more than once, and that is not you want).

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