Skip to main content
 首页 » 编程设计

python之从 gui 启动和停止线程

2024年12月31日27lexus

我目前正在开发一个带有 GUI 的程序,用于从传感器收集数据并在 GUI 中将其可视化。 来自传感器的数据存储在列表中以供进一步计算。

我目前正在尝试做的是在新线程中启动日志记录过程。 这应该会阻止 GUI 卡住。

我当前的代码:

import tkinter as tk 
import time 
import threading 
 
class GUI: 
    def __init__(self, tk_object): 
        self.gui = tk_object 
        self.gui.title("Logger")  
        self.gui.resizable(width=True, height=True) 
 
        self.testlabel = tk.Label(self.gui, text="Recording in process") 
        self.testlabel.grid(row = 7, column = 0) 
        self.testlabel.config(bg='white') 
 
        btn1 = tk.Button(master, text="Start Recording", width=16, height=5, command=lambda: self.start_functions()) 
        btn1.grid(row=2,column=0) 
        btn2 = tk.Button(master, text="Stop Recording", width=16, height=5, command=lambda: self.stop_functions()) 
        btn2.grid(row=3,column=0) 
 
    def start_functions(self): 
        """Calls the method get_sample in a new thread and changes the bg-color of the label to red"""  
        Thread_1 = threading.Thread(target=self.get_sample(), name='Thread1')         
        Thread_1.start() 
        self.testlabel.config(bg='red')  
 
    def stop_functions(self): 
        """Stops all active threads and changes bg-color of the label back to white"""  
        #stop_threads = threading.Event() 
        #stop_threads.set() 
        threading.Event().set() 
        self.testlabel.config(bg='white')             
 
    def get_sample(self): 
        """get data and append it to a list""" 
        while not threading.Event().is_set(): 
            time.sleep(1) 
            res_cel.append(res_cel[-1]+1) 
            x_value.append(x_value[-1]+1) 
        print(res_cel) 
        print(x_value)  
 
 
master = tk.Tk() 
master_object = GUI(master) 
master.mainloop() 

目前,get_sample 方法包含一个占位符。 我正在尝试通过 Event() 处理程序停止 Thread1(get_sample 方法在其中运行)。

while not threading.Event().is_set(): 

这似乎无法正常工作。 有更好的方法吗? 在这种方法之前,我尝试使用 class 来处理线程(这是在 stackoverflow 上找到的,但我似乎再也找不到了,抱歉):

class Controller(object): 
 
def __init__(self): 
    self.thread1 = None 
    self.stop_threads = Event() 
 
def run(self): 
    .. do somehting 

并通过以下方式启动/停止线程:

def starting_thread(self): 
    self.stop_threads.clear() 
    self.thread1 = Thread(target = self.run) 
    self.thread1.start() 
 
def stopping_thread(self): 
    self.stop_threads.set() 
    self.thread1 = None 

注意:这些函数在 Controller 类中。 使用此解决方案,我无法更改 GUI 类中的标签背景颜色,因为它不知道它引用的是什么对象。

我是 Python 编程的新手,所以如果有人能向我解释我在这里缺少什么,我会很高兴。

谢谢 x土星

请您参考如下方法:

您最好创建自己的 Thread 对象并提供停止它的方法。线程在执行其 run 方法时停止运行。看下面的例子

import time 
import tkinter as tk 
from threading import Thread 
 
class MyThread(Thread): 
    thread_running = False 
 
    def run(self): 
        k = 0 
        self.thread_running = True 
        while self.thread_running: 
            print(k) 
            k +=1 
            time.sleep(1) 
        print("thread ended") 
 
    def stop(self): 
        self.thread_running = False 
 
 
class Window(tk.Tk): 
    def __init__(self): 
        tk.Tk.__init__(self) 
 
        self.thread = None 
 
        tk.Button(self, text="launch thread", command=self.launch_thread)\ 
            .grid(row=1, column=0) 
        tk.Button(self, text="stop thread", command=self.stop_thread)\ 
            .grid(row=2, column=0) 
 
    def launch_thread(self): 
        if self.thread: 
            print("thread already launched") 
        else: 
            print("thread launched") 
            self.thread = MyThread() 
            self.thread.start() 
 
 
    def stop_thread(self): 
        if self.thread: 
            self.thread.stop() 
            self.thread = None 
        else: 
            print("no thread running") 
 
if __name__ == '__main__': 
    win = Window() 
    win.mainloop() 

有关详细信息,请参阅此主题 Is there any way to kill a Thread?