为什么我的tkinter倒计时计时器在达到零时不能自动启动?

2024-05-13 11:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个倒计时计时器,当它达到零时会自动重置,然后再次开始倒计时。我已经根据另一个用户的代码进行了非常轻微的修改,但是我遗漏了一些东西

from tkinter import *
from tkinter import ttk
from tkinter import font
import time
import datetime

global endTime
global taktTime

def quit(*args):
    root.destroy()

def show_time():
    # Get the time remaining until the event
    remainder = endTime - datetime.datetime.now()
    # remove the microseconds part
    remainder = remainder - datetime.timedelta(microseconds=remainder.microseconds)
    if remainder.days >= 0:
        # Show the time left
        txt.set(remainder)
        # Trigger the countdown after 1000ms
        root.after(1000, show_time)
    else:
        txt.set('complete')
        endTime = datetime.datetime.now() + taktTime

# Use tkinter lib for showing the clock
root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
root.bind("x", quit)
root.after(1000, show_time)

taktTime = datetime.timedelta(seconds=10)

# Set the end date and time for the countdown
endTime = datetime.datetime.now() + taktTime

fnt = font.Font(family='Helvetica', size=250, weight='bold')
txt = StringVar()
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="white", background="black")
lbl.place(relx=0.5, rely=0.5, anchor=CENTER)

root.mainloop()

当余数为零时,我试图重置endTime,但得到一个错误“UnboundLocalError:赋值前引用的局部变量'endTime'”

我相信这是一个简单的初学者错误,所以提前感谢您的帮助


Tags: thefromimporttxtdatetimetimetkintershow