如何停止tkinter定时器功能,当我按下按钮多一次?



我试图使用root.after_cancel(AFTER),但我不知道如何。

root.after_cancel(AFTER) 
AFTER = None
def countdown(count,time,name):
global AFTER
time['text'] =name,":",datetime.fromtimestamp(count).strftime("%M:%S")
if count > 0 :
AFTER = root.after(1000, countdown, count-1,time,name)
elif count == 0 :
time['text'] = f"Возрожден:{name}"``` 

很难猜出你到底在找什么,但是……下面的工作代码输出到标准输出,并能够启动/停止/重启倒计时与按下[Countdown]按钮。"诀窍"是一直运行计时器检查全局变量的值,按下按钮将根据当前值设置该变量的值。代码的工作方式似乎是你的两个问题的答案(1)。如何停止和2。如何通过按下开始倒计时的按钮来重置倒计时) .

def countdown():
global countdownValue
if countdownValue > 0 :
print(' countdown: ', countdownValue)
countdownValue -= 1
if countdownValue == 0 :
countdownValue = -1
print(f"n  Возрожден:  {name} :) ")
root.after(1000, countdown)
def startStopCountdown():
global countdownValue
if countdownValue > 0:
print('stopCountdown')
countdownValue = -1
else: 
print('startCountdown')
countdownValue = 10
import tkinter as tk
countdownValue = -1
name           = 'Возро'

root = tk.Tk()
root.title("3,2,1,...")
btn = tk.Button( root, text="Countdown", font=('',20), 
command=startStopCountdown)
btn.grid()
countdown()
root.mainloop()

顺便说一句:在你的问题的上下文中,我想到以下可能对你的问题有所帮助:使用tkinter添加标签/文本(理想情况下位于倒计时计时器上方)。

最新更新