如何建立 Tkinter GUI 停止按鈕來打破無限迴圈?
Tkinter 是一個用於建立基於 GUI 的應用程式的 Python 庫。假設我們要建立一個功能性的應用程式,其中一個特定函式在一個迴圈中定義。這個遞迴函式將會在一個 Label widget 中無限次地顯示一些文字。
為了停止這個遞迴函式,我們可以定義一個函式,它會在每次單擊一個按鈕時更改條件。條件可以透過宣告一個全域性變數來更改,該變數可以是 True 或 False。
示例
# Import the required library from tkinter import * # Create an instance of tkinter frame win= Tk() # Set the size of the Tkinter window win.geometry("700x350") # Define a function to print something inside infinite loop run= True def print_hello(): if run: Label(win, text="Hello World", font= ('Helvetica 10 bold')).pack() # After 1 sec call the print_hello() again win.after(1000, print_hello) def start(): global run run= True def stop(): global run run= False # Create buttons to trigger the starting and ending of the loop start= Button(win, text= "Start", command= start) start.pack(padx= 10) stop= Button(win, text= "Stop", command= stop) stop.pack(padx= 15) # Call the print_hello() function after 1 sec. win.after(1000, print_hello) win.mainloop()
輸出
現在,每當我們單擊“停止”按鈕時,它將停止呼叫函式。
廣告