繁体   English   中英

使用 Tkinter 按钮停止迭代函数

[英]Using Tkinter button to stop an iterating function

我创建了一个带有“停止”按钮的 GUI。 当 GUI 运行时,另一个模块被调用,其中包含一个后台函数的 while 循环。 停止按钮将用于将变量传递给循环以停止它。 但是,当调用包含循环的模块时,GUI 会冻结。 我曾考虑使用库“线程”,但找不到任何 tkinter 特定内容。 任何关于如何创建代码的建议或小例子都会有很大帮助。

这只是一个示例程序,用于说明如何杀死正在运行的线程。

    import threading 
    import time 

    def run(): 
        while True: 
            print('thread running') 
            global stop_threads 
            if stop_threads: 
                break



    if __name__=="__main__":
        stop_threads = False
        t1 = threading.Thread(target = run) ##background loop
        t1.start() 
        time.sleep(1) 
        #while clicking on the button in GUI kill the thread like this
        stop_threads = True 
        t1.join() 
        print('thread killed')

这是一个带有 2 个按钮的基本 GUI,可以启动和停止增加变量count的线程。

我让你试试:

import tkinter as tk
import threading
import time

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("test")
        self.button_start = tk.Button(self, text="Start", command=self.start_thread)
        self.button_start.pack()
        self.button_stop = tk.Button(self, text="Stop", command=self.stop_thread)
        self.button_stop.pack()
        self.count = 0
        self.continue_thread = True


    def start_thread(self):
        self.count = 0
        self.continue_thread = True

        self.t1 = threading.Thread(target = self.counter)
        self.t1.daemon = True # With this parameter, the thread functions stops when you stop the main program
        self.t1.start()

    def stop_thread(self):
        self.continue_thread = False
        self.t1.join()

    def counter (self):
        while self.continue_thread:
            print("i =", self.count)
            self.count += 1
            time.sleep(1)

if __name__ == "__main__":
    app = GUI()
    app.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM