GUI does not update from another thread when using PyGtk

I use PyGTK to create a GUI application. I want to update a textview widget from another thread, but the widget does not update every time I try to update. What should I do to get a reliable GUI update?

+6
python multithreading pygtk
source share
4 answers

GTK + is not thread safe, so you shouldn't just call GUI update methods from other threads. glib.idle_add (or gobject.idle_add in older versions of PyGTK) can be used for this purpose.

Instead of writing:

label.set_text("foo") 

you write:

 glib.idle_add(label.set_text, "foo") 

which calls a function call in GTK +.

If you need to run multiple statements, it is often easier to wrap them in functions:

 def idle(): label1.set_text("foo") label2.set_text("bar") glib.idle_add(idle) 

Make sure that the function passed to idle_add does not return True ; otherwise it will be queued again.

Edit: As Daniel noted, you first need to call gtk.gdk.threads_init() anywhere in your program.

+12
source share

As indicated in previous answers, GTK is not "thread safe", but it "supports thread" - see this page under the "Themes" section: https://developer.gnome.org/gdk2/stable/gdk2-Threads.html

To modify GTK widgets from another thread, you must use GTK lock. Call gtk.threads_init() immediately after importing the gtk module, and then you can update it like this:

 gtk.threads_enter() # make changes... gtk.threads_leave() 

Please note that the above will not work on Windows (see link above). On Windows, you should use gobject.idle_add() as described above, but be sure to put gobject.threads_init() immediately after importing gobject into your code! The idle_add () function will perform the update itself in the main thread (the thread works with gtk.main ()).

+2
source share

the same can be achieved using the gobject.idle_add method, the syntax of which is similar to the above, you need to import the gobject module

-one
source share

What Johannes said is true, however, since GTK is a wrapper for glib and gobjects, you really want to use gtk.idle_add (). No need for unnecessary imports.

-one
source share

All Articles