如何在 Tkinter 中使用停止按鈕停止迴圈?
考慮一個在迴圈中執行程序的情況,我們希望在單擊按鈕時停止迴圈。通常,在程式語言中,為了停止連續的while迴圈,我們使用break語句。但是,在 Tkinter 中,我們使用after()來代替while迴圈,從而在迴圈中執行定義的函式。要中斷連續迴圈,可以使用一個全域性布林變數,該變數可以更新以更改迴圈的執行狀態。
對於給定的示例,
建立一個類似於迴圈中標誌的全域性變數。
定義兩個按鈕,開始和停止,用於啟動和停止執行。
定義兩個函式,on_start()和on_stop(),用於向迴圈傳遞更新。
示例
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") running = True # Define a function to print the text in a loop def print_text(): if running: print("Hello World") win.after(1000, print_text) # Define a function to start the loop def on_start(): global running running = True # Define a function to stop the loop def on_stop(): global running running = False canvas = Canvas(win, bg="skyblue3", width=600, height=60) canvas.create_text(150, 10, text="Click the Start/Stop to execute the Code", font=('', 13)) canvas.pack() # Add a Button to start/stop the loop start = ttk.Button(win, text="Start", command=on_start) start.pack(padx=10) stop = ttk.Button(win, text="Stop", command=on_stop) stop.pack(padx=10) # Run a function to print text in window win.after(1000, print_text) win.mainloop()
輸出
執行以上程式碼以測試特定條件下的迴圈。
如果執行以上程式碼並單擊“開始”按鈕,則它將在迴圈中列印“Hello World”文字,可以透過單擊“停止”按鈕來停止。
Hello World Hello World Hello World Hello World Hello World Process finished with exit code 0
廣告