[英]How to exit from a "window.after" loop?
I'm trying to understand how to exit from a "loop", I made this code in Tkinter just to understand, when i press start
the loop begins and it repeats the 3 prints every 1 second.我试图了解如何从“循环”中退出,我在 Tkinter 中制作了这段代码只是为了理解,当我按下
start
,循环开始并且它每 1 秒重复 3 次打印。 Is it possible to exit from the start
loop pressing the stop
button in some way?是否可以以某种方式按下
stop
按钮退出start
循环?
from tkinter import *
cycle = True
def start():
if cycle == True:
print("1")
window.after(1000,start)
cycle = True
def stop():
global cycle
cycle = False
window = Tk()
window.geometry("200x200")
button1 = Button(window,text="Start",command=start)
button1.pack()
button2 = Button(window,text="Stop",command=stop)
button2.pack()
window.mainloop()
I solved the problem by adding an extra function and calling the function before mainloop().我通过添加一个额外的函数并在 mainloop() 之前调用该函数解决了这个问题。
from tkinter import *
cycle = True
def print_text():
if cycle:
print("Hello World")
window.after(1000, print_text)
def start():
global cycle
cycle = True
def stop():
global cycle
cycle = False
window = Tk()
window.geometry("200x200")
button1 = Button(window,text="Start",command=start)
button1.pack()
button2 = Button(window,text="Stop",command=stop)
button2.pack()
window.after(1000, print_text)
window.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.