簡體   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