简体   繁体   English

使用 Tkinter 按钮停止迭代函数

[英]Using Tkinter button to stop an iterating function

I have created a GUI with a "stop" button.我创建了一个带有“停止”按钮的 GUI。 When the GUI is ran, another module is called that contains a while loop for a background function.当 GUI 运行时,另一个模块被调用,其中包含一个后台函数的 while 循环。 The stop button would be used to pass a variable to the loop to stop it.停止按钮将用于将变量传递给循环以停止它。 However, when the module containing the loop is called the GUI freezes.但是,当调用包含循环的模块时,GUI 会冻结。 I have considered using the library "threading" but cannot find any tkinter specific content.我曾考虑使用库“线程”,但找不到任何 tkinter 特定内容。 Any advice or small example of how you would create the code would help a lot.任何关于如何创建代码的建议或小例子都会有很大帮助。

This is just a sample program to illustrate how to kill a running thread.这只是一个示例程序,用于说明如何杀死正在运行的线程。

    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')

Here is a basic GUI with 2 buttons that can start and stop a thread which increments a variable count .这是一个带有 2 个按钮的基本 GUI,可以启动和停止增加变量count的线程。

I let you try it :我让你试试:

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