wxPython、线程与模块间的PostEvent
我对wxPython还算是个新手(但对Python本身不陌生),所以如果我漏掉了什么,请多包涵。
我正在写一个图形界面应用程序,基本上就是有“开始”和“停止”两个按钮,用来启动和停止一个线程。这个线程是个无限循环,只有在停止线程时才会结束。这个循环会生成一些消息,目前只是用print
输出。
我的图形界面类和无限循环(使用threading.Thread
作为子类)放在不同的文件里。请问有什么好的方法让线程能把更新推送到图形界面里的TextCtrl
吗?我试过PostEvent
和Queue
,但都没什么效果。
这里有一些简单的代码,删掉了一些部分以保持简洁:
main_frame.py
import wx
from loop import Loop
class MainFrame(wx.Frame):
def __init__(self, parent, title):
# Initialise and show GUI
# Add two buttons, btnStart and btnStop
# Bind the two buttons to the following two methods
self.threads = []
def onStart(self):
x = Loop()
x.start()
self.threads.append(x)
def onStop(self):
for t in self.threads:
t.stop()
loop.py
class Loop(threading.Thread):
def __init__(self):
self._stop = threading.Event()
def run(self):
while not self._stop.isSet():
print datetime.date.today()
def stop(self):
self._stop.set()
之前我有过一次成功的经验,是把类放在同一个文件里,使用wx.lib.newevent.NewEvent()
,大概是沿着这样的思路。如果有人能给我指个方向,我会非常感激。
1 个回答
2
最简单的解决办法就是使用 wx.CallAfter
wx.CallAfter(text_control.SetValue, "some_text")
你可以从任何线程调用 CallAfter
,而你传给它的函数会在主线程中被调用。