如何创建一个Tkinter GUI停止按钮来打断无限循环?
Tkinter是一个Python库,用于创建基于GUI的应用程序。假设我们必须创建一个功能性的应用程序,在其中一个特定的函数在循环中定义。递归函数将为无限次在Label小部件中显示一些文本。
为了停止这个递归函数,我们可以定义一个函数,每当单击按钮时就更改条件。该条件可以通过声明一个全局变量来更改,该变量可以是True或False。
示例
# 导入所需的库
from tkinter import *
# 创建一个Tkinter框架实例
win = Tk()
# 设置Tkinter窗口的大小
win.geometry("700x350")
# 定义一个函数,在无限循环中打印一些东西
run = True
def print_hello():
if run:
Label(win, text="Hello World", font=('Helvetica 10 bold')).pack()
# 每隔1秒再次调用print_hello()
win.after(1000, print_hello)
def start():
global run
run = True
def stop():
global run
run = False
# 创建按钮以触发循环的开始和结束
start = Button(win, text="开始", command=start)
start.pack(padx=10)
stop = Button(win, text="停止", command=stop)
stop.pack(padx=15)
# 在1秒后调用print_hello()函数。
win.after(1000, print_hello)
win.mainloop()
输出
现在,每当我们单击“停止”按钮时,它将停止调用该函数。