我在 Windows 上遇到线程和 PyGTK 问题。根据PyGTK FAQ(和我自己的实验),从子线程可靠地更新 GUI 的唯一方法是使用该gobject.idle_add
函数。但是,不能保证何时调用此函数。我如何保证在gobject.idle_add
它指向的函数之后调用后面的行?
非常简单和人为的例子:
import gtk
import gobject
from threading import Thread
class Gui(object):
def __init__(self):
self.button = gtk.Button("Click")
self.button.connect("clicked", self.onButtonClicked)
self.textEntry = gtk.Entry()
self.content = gtk.HBox()
self.content.pack_start(self.button)
self.content.pack_start(self.textEntry)
self.window = gtk.Window()
self.window.connect("destroy", self.quit)
self.window.add(self.content)
self.window.show_all()
def onButtonClicked(self, button):
Thread(target=self.startThread).start()
def startThread(self):
#I want these next 2 lines to run in order
gobject.idle_add(self.updateText)
print self.textEntry.get_text()
def updateText(self):
self.textEntry.set_text("Hello!")
def quit(self, widget):
gtk.main_quit()
gobject.threads_init()
x = Gui()
gtk.main()