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

来源:互联网 发布:Execl数据分析证书 编辑:程序博客网 时间:2024/05/16 08:43

界面和多线程一向是编程里比较难的地方,常见的做法一般是界面一个线程,后台新开一个工作线程,这两个线程进行通信,这样可以让界面不至于为响应。在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()  
0 0
原创粉丝点击