Py学习  »  Python

python tkinter-显示和执行不同进程的多个窗口

dayDreamer • 5 年前 • 2434 次点击  

我有一个GUI应用程序。它有不止一扇窗户。主窗口每秒都在用新值更新。我在这里使用线程和队列。主窗口有一个按钮。按下它将打开一个新窗口。我想要的是,当显示新窗口时,停止主窗口中的进程(更新值进程),一些新进程将显示在新窗口中。关闭新窗口将再次撤消主窗口并继续该过程。我需要使用多线程还是多处理? 不幸的是,我是第二次问这个问题。很抱歉。

import tkinter
import time
import threading
import random
import queue

class GuiPart:
    def __init__(self, master, queue, endCommand,newWindow):
        self.queue = queue
        self.pause = False
        # Set up the GUI
        console = tkinter.Button(master, text='Done', command=endCommand)
        console.pack()

        console2 = tkinter.Button(master, text='New', command=newWindow)
        console2.pack()

        self.output = tkinter.StringVar()
        #output.set(1)
        output_1_label = tkinter.Label(master, textvariable= self.output, height=2, width=12)
        output_1_label.pack()
        # Add more GUI stuff here
        self.temp_process()

    def temp_process(self):
        if not self.pause:
            print ("handling messages")
        else:
            print ("Not handling messages")
        root.after(1000,self.temp_process)


    def processIncoming(self):
        while self.queue.qsize():
            try:
                msg = self.queue.get(0)
                print (msg)
                self.output.set(msg)
            except queue.Empty:
                pass

class ThreadedClient:

    def __init__(self, master):
        self.master = master

        # Create the queue
        self.queue = queue.Queue()

        # Set up the GUI part
        self.gui = GuiPart(master, self.queue, self.endApplication,self.create_window)

        self.running = 1
        self.thread1 = threading.Thread(target=self.workerThread1)  #this is for sending data to queue.
# what about second window?
        self.thread1.start()
        self.periodicCall()

    def on_quit(self):
        self.gui.pause = False
        self.window.destroy()

    def create_window(self):
        self.window = tkinter.Toplevel(root)
        self.gui.pause = True
        self.window.protocol("WM_DELETE_WINDOW",self.on_quit)

    def periodicCall(self):
        self.gui.processIncoming()
        if not self.running:
            import sys
            sys.exit(1)
        self.master.after(1000, self.periodicCall)

    def workerThread1(self):
        while self.running:
            time.sleep(rand.random() * 1)
            msg = rand.random()
            self.queue.put(msg)

    def endApplication(self):
        self.running = 0
rand = random.Random()
root = tkinter.Tk()
client = ThreadedClient(root)
root.mainloop()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50981
 
2434 次点击  
文章 [ 1 ]  |  最新文章 5 年前