您可以使用wxpython附帶的pubsub - wx.lib.pubsub
。請參閱my answer here以獲取線程間通信使用的基本示例。
對於可選:你如何使用wx.Yield
讓你的窗口更新的一個例子。
import wx
class GUI(wx.Frame):
def __init__(self, parent, title=""):
wx.Frame.__init__(self, parent=parent, title=title, size=(340,380))
self.SetMinSize((140,180))
self.creating_widgets = False
self.panel = wx.Panel(id=wx.ID_ANY, parent=self)
self.startButton = wx.Button(self.panel, wx.ID_ANY, 'Start')
self.stopButton = wx.Button(self.panel, wx.ID_ANY, 'Stop')
self.messageBox = wx.TextCtrl(self.panel, wx.ID_ANY, '', size=(75, 20))
self.Bind(wx.EVT_BUTTON, self.onStart, self.startButton)
self.Bind(wx.EVT_BUTTON, self.onStop, self.stopButton)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.startButton, 0, wx.ALL, 10)
self.sizer.Add(self.stopButton, 0, wx.ALL, 10)
self.sizer.Add(self.messageBox, 0, wx.ALL, 10)
self.panel.SetSizerAndFit(self.sizer)
def onStart(self, event):
self.creating_widgets = True
count = 0
self.startButton.Disable()
while self.creating_widgets:
count += 1
#Create your widgets here
#just for simulations sake...
wx.MilliSleep(100)
self.messageBox.SetLabel(str(count))
#Allow the window to update,
#You must call wx.yield() frequently to update your window
wx.Yield()
def onStop(self, message):
self.startButton.Enable()
self.creating_widgets = False
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = GUI(None)
frame.Show()
app.MainLoop()
我不知道是否有可能發送小部件對象,如果是這樣,它會是混亂的。你爲什麼不保存自己的麻煩,並在主線程中創建小部件,並使用子線程顯示進度對話框或其他內容...這將爲您節省很多麻煩。 – volting 2010-08-26 14:44:06
其實我必須在一次創建這麼多的小部件,如果我去創建主線程中的小部件,那麼它會凍結GUI。 – 2010-08-26 16:20:20
嗯,我不明白它會如何工作,我想你會很快發現,考慮使用wx.Yield方法定期更新窗口,作爲線程的替代方案.. Iv'e增加了一個基本示例我的回答 – volting 2010-08-26 17:17:32