2 回答
TA贡献1830条经验 获得超3个赞
您应该保留对调用的引用,并在isafter时取消回调。您可以通过使用可以读取或设置其值的对象的变量来避免丑陋的声明。toggleFalseglobaltkinter
import tkinter as tk
def toggle_on_off():
toggle.set(not toggle.get())
if toggle.get():
watch()
def watch():
count_seconds.set(count_seconds.get() + 1)
if toggle.get():
_callback_id.set(root.after(1000, watch))
else:
root.after_cancel(_callback_id.get())
root = tk.Tk()
count_seconds = tk.IntVar(root)
count_seconds.set(0)
toggle = tk.BooleanVar(root)
toggle.set(False)
Button(root,text="Start",command=toggle_on_off).pack()
label = tk.Label(root, textvariable=count_seconds)
label.pack()
_callback_id = tk.StringVar(root)
_callback_id.set(None)
root.mainloop()
[编辑]
与全局变量相同的代码是这样的:
import tkinter as tk
def toggle_on_off():
global toggle
toggle = not toggle
if toggle:
watch()
def watch():
global count_seconds, _callback_id
count_seconds += 1
label.configure(text=str(count_seconds))
if toggle:
_callback_id = root.after(1000, watch)
else:
root.after_cancel(_callback_id)
root = tk.Tk()
count_seconds = 0
toggle = False
Button(root,text="Start",command=toggle_on_off).pack()
label = tk.Label(root, text=str(count_seconds))
label.pack()
_callback_id = None
root.mainloop()
TA贡献1831条经验 获得超9个赞
您可以添加一个全局变量,例如“exit”,
并在 l1.after(1000,watch) 之前添加 if 语句
def toggle():
global tog, exit
exit = False
tog = tog + 1
if tog == 1:
watch()
elif tog == 2:
stop()
tog = 0
def watch():
global sec
global hour
global mins
global exit
sec = sec + 1
l1.config(text=sec)
if not exit:
l1.after(1000,watch)
在 stop() 中,你可以写
def stop():
global exit
exit = True
添加回答
举报