python+Tkinter+多线程

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

import Tkinter,time,threading,random,Queue
class GuiPart():
    def __init__(self,master,queue,endCommand):
        self.queue=queue
        Tkinter.Button(master,text='Done',command=endCommand).pack()
    def processIncoming(self):
        while self.queue.qsize():
            try:
                msg=self.queue.get(0)
                print msg
            except Queue.Empty:
                pass
class ThreadedClient():
    def __init__(self,master):
        self.master=master
        self.queue=Queue.Queue()
        self.gui=GuiPart(master,self.queue,self.endApplication)
        self.running=True
        self.thread1=threading.Thread(target=self.workerThread1)
        self.thread1.start()
        self.periodicCall()
    def periodicCall(self):
        self.master.after(200,self.periodicCall)
        self.gui.processIncoming()
        if not self.running:
            self.master.destroy()
    def workerThread1(self):
        #self.ott=Tkinter.Tk()
        #self.ott.mainloop()
        while self.running:
            time.sleep(rand.random()*1.5)
            msg=rand.random() 
            self.queue.put(msg)
    def endApplication(self):
        self.running=False
rand=random.Random()
root=Tkinter.Tk()
client=ThreadedClient(root)
root.mainloop()


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页