开发者

GUI not updated from another thread when using PyGtk

开发者 https://www.devze.com 2022-12-17 12:23 出处:网络
I am using PyGTK to build a GUI application. I want to update the textview widget 开发者_StackOverflow中文版from another thread but the widget is not getting updated everytime i try an update. What sh

I am using PyGTK to build a GUI application. I want to update the textview widget 开发者_StackOverflow中文版from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?


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

Instead of writing:

label.set_text("foo")

you would write:

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

which causes the function call to be queued in GTK+.

If you need to run multiple statements, it's often easier to wrap them in a function:

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 pointed out, you need to call gtk.gdk.threads_init() anywhere in your program first.


As stated in the previous answers, GTK is not "thread safe," but it is "thread-aware" - see this page on Threads: https://developer.gnome.org/gdk2/stable/gdk2-Threads.html

In order to modify GTK widgets from another thread you have to use GTK's locking. Call gtk.threads_init() immediately after importing the gtk module, and then you can update like so:

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

Note that the above will not work on Windows (see the link above). On Windows you must use gobject.idle_add() as explained above, though don't forget to put gobject.threads_init() directly after importing gobject in your code! The idle_add() function will execute the update itself in the main thread (the thread running gtk.main()).


the same may be achieved using gobject.idle_add method whose syntax is same as above,you have to import the module gobject


What Johannes said is correct, however since GTK is a wrapper for the glib and gobject things, you would actually want to use gtk.idle_add(). No need for the unnecessary imports.

0

精彩评论

暂无评论...
验证码 换一张
取 消