Python本身有一个threading的多线程库,非常好用。


同时还有一个线程安全的列队库Queue。使用Quete列队,就可以在多个线程之间传递消息了。


threading.Event()在主线程或者其他线程中启动另一个线程.这样作之后,我们就可以把和GUI无关的所有工作都放在别的线程处理,只在主线程进行GUI相关的显示数据绘制.


wxPython有一个子线程调用主线程UI控件的方法wx.CallAfter(),子线程调用这个方法之后,主线程的UI可以在当前事件处理结束后处理子线程发送的消息,这是wxPython中子线程给主线程发送消息最简单的方法了。


看的一个关于wxPython教程中给出了一个例子:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import
import

class
'''
This just simulates some long-running task that periodically sends a message to the GUI thread.
'''
def
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.timeToQuit = threading.Event()
self.timeToQuit.clear()
10,20)
0.1 + 2.0
def
self.timeToQuit.set()
def run(self):#运行一个线程
'Thread %d iterating %d times with a delay of %1.4f\n'%(self.threadNum, self.messageCount, self.messageDelay)
wx.CallAfter(self.window.LogMessage, msg)
for i in range(1, self.messageCount+1):
self.timeToQuit.wait(self.messageDelay)
if
break
'Message %d from thread %d\n'
wx.CallAfter(self.window.LogMessage, msg)
else:
wx.CallAfter(self.window.ThreadFinished, self)
class
def
None, title='Multi-threaded GUI')
self.threads = []
0
panel = wx.Panel(self)
1, 'Start a thread')
1, 'Stop all threads')
1, 'Worker Threads: 00')
1, '',style=wx.TE_RICH|wx.TE_MULTILINE)
inner = wx.BoxSizer(wx.HORIZONTAL)
0, wx.RIGHT, 15)
0, wx.RIGHT, 15)
0, wx.ALIGN_CENTER_VERTICAL)
main = wx.BoxSizer(wx.VERTICAL)
0, wx.ALL, 5)
1, wx.EXPAND|wx.ALL, 5)
panel.SetSizer(main)

self.Bind(wx.EVT_BUTTON, self.OnStartButton, startBtn)
self.Bind(wx.EVT_BUTTON, self.OnStopButton, stopBtn)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

self.UpdateCount()
def
1
#创建一个线程
self.threads.append(thread)
self.UpdateCount()
#启动线程
def
self.StopThreads()
self.UpdateCount()
def
self.StopThreads()
self.Destroy()
def StopThreads(self):#从池中删除线程 while self.threads:
0]
thread.stop()
self.threads.remove(thread)
def
'Worker Threads: %d'
def LogMessage(self, msg):#注册一个消息
self.log.AppendText(msg)
def ThreadFinished(self, thread):#删除线程
self.threads.remove(thread)
self.UpdateCount()
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()

下边是运行结果截图: