I’m displaying a sensor system’s measurement values utilizing the Tkinter GUI utility. The sensor sends new information each second. I began a brand new thread and put the end in a Queue and course of the queue to show the values on GUI. Now I’m going through one other downside. The sensor has two modes of operations. For simplicity, I’ve used a random generator in this system. Customers ought to have the ability to change the modes utilizing two buttons. Button-1 for Mode-1, Button-2 for Mode-2. (say the mode-1 operation is random.randrange(0,10) and mode-2 operation is random.randrange(100, 200). How do I management these two operations by Threading? if a consumer began a mode-1 operation, when he presses the Button-2, the mode-1 operation ought to cease (thread-1) and mode-2 operation (thread-2) ought to begin. Does it imply do I have to kill thread-1? Or is there any technique to management two modes in similar thread? I’m completely new into threading. Any ideas, please.
import tkinter import threading import queue class GuiGenerator: def __init__(self, grasp, queue): self.queue = queue # Arrange the GUI grasp.geometry('800x480') self.output = tkinter.StringVar() #I have never proven command components in following buttons. No thought methods to use it to witch modes? mode_1_Button = tkinter.Button(grasp, textual content = "Mode-1") mode_1_Button.place(x=600, y=300) mode_2_Button = tkinter.Button(grasp, textual content = "Mode-2") mode_2_Button.place(x=600, y=400) def processQueue(self): whereas self.queue.qsize(): attempt: sensorOutput = self.queue.get() #Q worth self.output.set(sensorOutput) #Show Q worth on GUI besides queue.Empty: move class ClientClass: def __init__(self, grasp): self.grasp = grasp # Create the queue self.queue = queue.Queue() # Arrange the GUI half self.myGui = GuiGenerator(grasp, self.queue) #How do I change the modes of operations? do I want some flags setting by button press? # Arrange the thread to do asynchronous I/O self.thread1_mode1 = threading.Thread(goal=self.firstModeOperation) self.thread1_mode1.begin() # Begin the periodic name within the GUI to examine if the queue comprises # something new self.periodicCall() def periodicCall(self): # Verify each 1000 ms if there's something new within the queue. self.GuiGenerator.processQueue() self.grasp.after(1000, self.periodicCall) def firstModeOperation(self): whereas True: #??? how do i management right here by mode choice time.sleep(1.0) msg_mode_1= random.randrange(0,10) self.queue.put(msg_mode_1) def secondModeOperation(self): whereas True: #??? how do i management right here by mode choice time.sleep(1.0) msg_mode_2= random.randrange(0,10) self.queue.put(msg_mode_2) #Operation half root = tkinter.Tk() consumer = ClientClass(root) root.mainloop()