使用PyGtk时未从其他线程更新GUI [英] GUI not updated from another thread when using PyGtk
问题描述
我正在使用PyGTK来构建GUI应用程序.我想从另一个线程更新textview窗口小部件,但是每次我尝试更新时该窗口小部件都不会更新.我应该怎么做才能获得可靠的GUI更新?
I am using PyGTK to build a GUI application. I want to update the textview widget 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 +并非线程安全的,因此您不应简单地从其他线程调用GUI更新方法. glib.idle_add (或gobject.idle_add在较旧的PyGTK版本中)可以用于此目的.
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.
代替写作:
label.set_text("foo")
您会写:
glib.idle_add(label.set_text, "foo")
这会使函数调用在GTK +中排队.
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)
确保传递给idle_add
的函数不返回True
;否则它将再次排队.
Make sure that the function passed to idle_add
does not return True
; otherwise it will be queued again.
正如Daniel指出的那样,您需要先在程序中的任何位置调用gtk.gdk.threads_init()
.
As Daniel pointed out, you need to call gtk.gdk.threads_init()
anywhere in your program first.
这篇关于使用PyGtk时未从其他线程更新GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!