wxpython多线程_wxpython笔记:wxpython中的多线程实现

#-*- encoding:UTF-8 -*-

importwximportthreadingimportrandomclassWorkerThread(threading.Thread):'''This just simulates some long-running task that periodically sends

a message to the GUI thread.

561 / 565'''

def __init__(self,threadNum,window):

threading.Thread.__init__(self)

self.threadNum=threadNum

self.window=window

self.timeToQuit=threading.Event()

self.timeToQuit.clear()

self.messageCount= random.randint(10,20)

self.messageDelay= 0.1 + 2.0*random.random()#运行一个线程

defrun(self):

msg= "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 self.timeToQuit.isSet():#判断是否设置了标志位

breakmsg= "Message %d from thread %d\n" %(i,self.threadNum)

wx.CallAfter(self.window.LogMessage,msg)else:

wx.CallAfter(self.window.ThreadFinished,self)#暂停所有线程

defstop(self):

self.timeToQuit.set()classMyFrame(wx.Frame):def __init__(self):

wx.Frame.__init__(self,None,title="Multi-threaded GUI")

self.threads=[]

self.count=0

panel=wx.Panel(self)

startBtn=wx.Button(panel,-1,"Start a thread")

stopBtn=wx.Button(panel,-1,"Stop all threads")

self.tc=wx.StaticText(panel,-1,"Worker Threads: 00")

self.log=wx.TextCtrl(panel,-1,"",style=wx.TE_RICH|wx.TE_MULTILINE)

inner=wx.BoxSizer(wx.HORIZONTAL)

inner.Add(startBtn,0,wx.RIGHT,15)

inner.Add(stopBtn,0,wx.RIGHT,15)

inner.Add(self.tc,0,wx.ALIGN_CENTER_VERTICAL)

main=wx.BoxSizer(wx.VERTICAL)

main.Add(inner,0,wx.ALL,5)

main.Add(self.log,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()defOnStartButton(self,evt):

self.count+=1thread=WorkerThread(self.count,self)#创建一个线程

self.threads.append(thread)

self.UpdateCount()

thread.start()#启动线程

defOnStopButton(self,evt):

self.StopThreads()

self.UpdateCount()defOnCloseWindow(self,evt):

self.StopThreads()

self.Destroy()def StopThreads(self):#从池中删除线程

whileself.threads:

thread=self.threads[0]

thread.stop()

self.threads.remove(thread)defUpdateCount(self):

self.tc.SetLabel("Worker Threads: %d"%len(self.threads))def LogMessage(self,msg):#注册一个消息

self.log.AppendText(msg)def ThreadFinished(self,thread):#删除线程

self.threads.remove(thread)

self.UpdateCount()

app=wx.App()

frm=MyFrame()

frm.Show()

app.MainLoop()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值