繁体   English   中英

如何让这个计时器正确倒计时?

[英]How do I get this timer to count down properly?

我正在尝试制作一个简单的 gui,您可以在其中按下按钮启动计时器,并看到它倒计时,类似于https://web.5217.app/ ,但我无法让计时器显示在 gui 中,任何帮助,将不胜感激。

这也是我的第一个问题,所以我可能做错了什么。

from tkinter import Tk, Button, DISABLED, Label, ACTIVE
import time

#main window configuration
root = Tk()
root.title ("PyDoro")
root.geometry ("400x400")
root.configure(bg = "#383838") 

#colours for the text
Colour1 = "#c4c4c4"
Colour2 = "#292828"

def Date(): #Defines the date for displaying under the clock
    day = time.strftime("%d")
    month = time.strftime("%b") # %B can be used for full month
    year = time.strftime("%Y")

    Calendar.config (text= day + " " + month + " " + year)

def clock(): # for creating the clock
    tizo = time.strftime("%X") #Find the time for your locale
    Time.config (text = tizo)
    Time.after (1000, clock)
    Date() #calling the Date because it makes sense to do it here

def Stop():
    print ("nothing")

def Start():
    time_left = (50)
    Stop.config (state = ACTIVE)
    timer = Label (root, text = time_left)
    timer.pack()

    for i in range (50):
        timer.config (text = time_left)
        Start.after (1000) # this waits for 1 minute (60000 miliseconds)
        #print (i) # This is just for debugging
        time_left = time_left - 1 
        print (time_left)
        




Start = Button (root, text = "Start!", fg = Colour1, bg = Colour2, padx = 40, command = Start)
Stop = Button (root, text = "stop", fg = Colour1, bg = Colour2, state = DISABLED)



Time = Label (root, text="", font = ("Helvetica", 50), fg = Colour1, bg = "#383838")
Time.pack (pady = 5)

Calendar = Label (root, font = ("Helvetica", 12), fg = Colour1, bg = "#383838")
Calendar.pack (pady = 5)

Start.pack (pady = 10)

Stop.pack (pady = 10)


clock()
root.mainloop() #Runs the program

将您的Start() function 替换为以下代码:

def Start():
    time_left = (50)
    Stop.config (state = ACTIVE)
    timer = Label (root, text = time_left)
    timer.pack()
    def update(time_left):
        timer['text'] = time_left
        if time_left > 0:
            root.after(1000, update, time_left-1)
    update(time_left)

创建 label 后,程序会调用名为 update 的 function,它将计时器 label 的文本设置为time_left 如果time_left大于 0,它将调用root.after ,并将time_left -1传递回更新 function。 这将使计时器倒计时,直到达到 0。

没有显示计时器Label的原因是因为显示器从未有机会更新。 要解决此问题,请尝试使用Start() function 如下所示,它调用通用小部件方法update_idletasks()在更改后对其进行更新。

def Start():
    time_left = 50
    Stop.config(state=ACTIVE)
    timer = Label(root, text=time_left)
    timer.pack()

    for i in range(50):
        timer.config(text=time_left)
        time_left -= 1
        root.update_idletasks()  # Update display.
        root.after(1000)  # Pause for 1000 milliseconds (1 second).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM