python+Tkinter+多线程 简单例子1

界面和多线程一向是编程里比较难的地方,常见的做法一般是界面一个线程,后台新开一个工作线程,这两个线程进行通信,这样可以让界面不至于为响应。在python中可以利用队列完成整体的架构设计。直接给大家看代码吧,一个简单实例,非常好地例子。

[python]  view plain  copy
  1. import Tkinter,time,threading,random,Queue  
  2. class GuiPart():  
  3.     def __init__(self,master,queue,endCommand):  
  4.         self.queue=queue  
  5.         Tkinter.Button(master,text='Done',command=endCommand).pack()  
  6.     def processIncoming(self):  
  7.         while self.queue.qsize():  
  8.             try:  
  9.                 msg=self.queue.get(0)  
  10.                 print msg  
  11.             except Queue.Empty:  
  12.                 pass  
  13. class ThreadedClient():  
  14.     def __init__(self,master):  
  15.         self.master=master  
  16.         self.queue=Queue.Queue()  
  17.         self.gui=GuiPart(master,self.queue,self.endApplication)  
  18.         self.running=True  
  19.         self.thread1=threading.Thread(target=self.workerThread1)  
  20.         self.thread1.start()  
  21.         self.periodicCall()  
  22.     def periodicCall(self):  
  23.         self.master.after(200,self.periodicCall)  
  24.         self.gui.processIncoming()  
  25.         if not self.running:  
  26.             self.master.destroy()  
  27.     def workerThread1(self):  
  28.         #self.ott=Tkinter.Tk()  
  29.         #self.ott.mainloop()  
  30.         while self.running:  
  31.             time.sleep(rand.random()*1.5)  
  32.             msg=rand.random()   
  33.             self.queue.put(msg)  
  34.     def endApplication(self):  
  35.         self.running=False  
  36. rand=random.Random()  
  37. root=Tkinter.Tk()  
  38. client=ThreadedClient(root)  
  39. root.mainloop()  
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值