在 tkinter Python 中使用 .after() 函数进行倒计时时钟后,标签没有更新



我正在使用GUI进行倒数计时器,并且正在尝试复制Windows 10导入计时器应用程序的GUI。GUI 部分几乎完成,只剩下执行部分:

def start_countdown():
global hours, minutes, seconds, timer
user_input = (int(hours)*60*60 + int(minutes)*60 + int(seconds))
timerrr = int(user_input)

while timerrr > 0:
minutes, seconds = divmod(timerrr, 60)
hours, minutes = divmod(minutes, 60)
timer.config(text=str(hours).zfill(2) + ":" + str(minutes).zfill(2) + ":" + str(seconds).zfill(2))
print(str(timer.cget("text")) + "r", end=str(timer.cget("text")))
time.sleep(1)
timerrr -= 1
timer.after(1, start_countdown)
if timerrr == 0:
print("r""time's up!!!")
showinfo("countdown clock", "Time's Up!!!")

这是应该在按下按钮时执行倒计时步骤的功能。当我使用.after()时,"计时器"标签不会每秒显示更新,但通过打印相同的内容,我可以看到倒计时在控制台/终端中工作。

你以错误的方式使用了after(),也不应该使用 while 循环和sleep(),因为它可能会阻塞主线程。

以下是修改后的start_countdown()

def start_countdown(timerrr=None):
'''
based on your code, 'hours', 'minutes', 'seconds' and 'timer'
should be already created in the global namespace
'''
if timerrr is None:
# initialize timerrr when start_countdown() is first called
timerrr = int(hours)*60*60 + int(minutes)*60 + int(seconds)
mins, secs = divmod(timerrr, 60)
hrs, mins = divmod(mins, 60)
timer['text'] = f'{hrs:02}:{mins:02}:{secs:02}'
if timerrr > 0:
timer.after(1000, start_countdown, timerrr-1)
else:
showinfo("countdown clock", "Time's up!!")

最新更新