0

我正在使用 Tkinter GUI 应用程序显示传感器设备的测量值。传感器每秒发送一次新数据。我启动了一个新线程并将结果放入队列并处理队列以在 GUI 上显示值。现在我面临另一个问题。传感器有两种操作模式。为简单起见,我在程序中使用了随机生成器。用户应该能够使用两个按钮来切换模式。按钮 1 用于模式 1,按钮 2 用于模式 2。(假设模式 1 操作是 random.randrange(0,10),模式 2 操作是 random.randrange(100, 200)。如何通过线程控制这两个操作?如果用户启动了模式 1 操作,当他按下 Button-2 时,模式 1 操作应该停止(线程 1),模式 2 操作(线程 2)应该开始。这是否意味着我需要杀死线程1?或者有什么方法可以在同一个线程中控制两种模式?我对线程完全陌生。请有任何建议。

import tkinter
import threading
import queue
import time
import random

class GuiGenerator:
    def __init__(self, master, queue):
        self.queue = queue
        # Set up the GUI
        master.geometry('800x480')
        self.output = tkinter.StringVar()
        output_label = tkinter.Label(master, textvariable= self.output)
        output_label.place(x=300, y=200)

#I haven't shown command parts in following buttons. No idea how to use it to witch modes?
        mode_1_Button  = tkinter.Button(master, text = "Mode-1")   
        mode_1_Button.place(x=600, y=300)
        mode_2_Button  = tkinter.Button(master, text = "Mode-2")
        mode_2_Button.place(x=600, y=400)

    def processQueue(self):
        while self.queue.qsize():
            try:              
                sensorOutput = self.queue.get() #Q value              
                self.output.set(sensorOutput)     #Display Q value on GUI                
            except queue.Empty:
                pass

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

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

# Set up the GUI part
        self.myGui = GuiGenerator(master, self.queue)

#How do I switch the modes of operations? do I need some flags setting through button press?

# Set up the thread to do asynchronous I/O       

        self.thread1_mode1 = threading.Thread(target=self.firstModeOperation)
        self.thread1_mode1.start()

        # Start the periodic call in the GUI to check if the queue contains
        # anything new
        self.periodicCall()

    def periodicCall(self):

        # Check every 1000 ms if there is something new in the queue.        
        self.myGui.processQueue()        
        self.master.after(1000, self.periodicCall)

    def firstModeOperation(self):        
        while True:                      #??? how do i control here through mode selection
            time.sleep(1.0)
            msg_mode_1= random.randrange(0,10)
            self.queue.put(msg_mode_1)

    def secondModeOperation(self):        
        while True:                      #??? how do i control here through mode selection
            time.sleep(1.0)
            msg_mode_2= random.randrange(100,200)
            self.queue.put(msg_mode_2)

#Operation part
root = tkinter.Tk()
client = ClientClass(root)
root.mainloop()

4

0 回答 0