使用线程安全方法更新 GUI。在 wxPython 中,有 3 个:
- wx.CallAfter
- wx.CallLater
- wx.PostEvent
您还应该查看 wxPython wiki 以获取有关 wxPython 和线程的信息:
我还写了一个关于这个主题的教程:
更新:这是一个简单的例子,它创建了 40 个线程和“进程”40 个组成的文件。当每个线程完成时,它会更新显示。但是,我没有看到你所说的问题。
import random
import time
import wx
from threading import Thread
from wx.lib.pubsub import Publisher
########################################################################
class TestThread(Thread):
"""Test Worker Thread Class."""
#----------------------------------------------------------------------
def __init__(self, fname, sleepAmt):
"""Init Worker Thread Class."""
Thread.__init__(self)
self.fname = fname
self.sleepAmt = sleepAmt
self.start() # start the thread
#----------------------------------------------------------------------
def run(self):
"""Run Worker Thread."""
# This is the code executing in the new thread.
time.sleep(self.sleepAmt)
msg = "%s finished in %s seconds!" % (self.fname, self.sleepAmt)
wx.CallAfter(Publisher().sendMessage, "update", msg)
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
self.updateText = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
self.btn = btn = wx.Button(panel, label="Start Thread")
btn.Bind(wx.EVT_BUTTON, self.onButton)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.updateText, 1, wx.ALL|wx.EXPAND, 5)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
# create a pubsub receiver
Publisher().subscribe(self.updateDisplay, "update")
#----------------------------------------------------------------------
def onButton(self, event):
"""
Runs the thread
"""
for i in range(40):
fname = "test%s.txt" % i
secs = random.choice(range(3, 15))
TestThread(fname, secs)
#----------------------------------------------------------------------
def updateDisplay(self, msg):
"""
Receives data from thread and updates the display
"""
data = msg.data + "\n"
self.updateText.WriteText(data)
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
我正在使用带有 wxPython 2.8.12.1 的 Python 2.6 在 Windows 7 上运行