wxPython gui 是一个循环,要使部分代码休眠而不导致 gui 休眠,需要多线程。
我会编写一个调用线程函数的函数,现在这是一个肮脏的例子,但应该向您展示需要做什么:
import wx
from threading import Thread
import time
from wx.lib.pubsub import setuparg1
from wx.lib.pubsub import pub as Publisher
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
self.SetTitle('This is a threaded thing')
self.st1 = wx.StaticText(self, label='', pos=(30, 10))
self.SetSize((250, 180))
self.Centre()
self.Show(True)
self.Bind(wx.EVT_MOVE, self.OnMove)
# call updateUI when the thread returns something
Publisher.subscribe(self.updateUI, "update")
def OnMove(self, evt):
''' On frame movement call thread '''
x, y = evt.GetPosition()
C = SomeClass()
C.runthread(x, y)
def updateUI(self, evt):
''' Update label '''
data = evt.data
self.st1.SetLabel(data)
class SomeClass:
def runthread(self, x,y):
''' Start a new thread '''
t = Thread(target=self._runthread, args=(x,y,))
t.start()
def _runthread(self, x,y):
''' this is a threaded function '''
wx.CallAfter(Publisher.sendMessage, "update", "processing...")
time.sleep(3)
wx.CallAfter(Publisher.sendMessage, "update", "%d, %d" % (x, y))
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
现在,只要您尝试移动“框架”/窗口,线程就会被初始化,并将返回窗口的当前位置。
wx.CallAfter() 是对 GUI 线程的线程安全调用,仅在 GUI 线程准备好接收时发送数据。Publisher-module 简化了将数据发送到我们的线程的任务。
我会建议阅读: http: //www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/