如何在标签中显示计时器剩余的当前时间?

时间:2019-07-31 04:55:40

标签: python tkinter timer

我为正在做的项目的一部分制作了计时器。我已经制作了计时器,但是我希望将计时器中剩余的时间打印到标签上。另外,如果这不是预期的,我想暂时在标签上,然后一秒钟后它会删除自己并放置新的剩余时间(我不希望它继续将时间打印在新行上另一个)。

我发现一篇帖子几乎是我想要做的,但是对我来说不起作用,我不得不更改一些功能并添加一些新功能。我不确定为什么它不起作用,但是我希望它有所不同,因为它的预设时间为10秒,我希望它成为用户的选择。链接:Making a countdown timer with Python and Tkinter?

class Application(Frame):
    def createWidgets(self):

        # More code here    

        self.timeLeftLabel = Label(root, text='Time Left: ')
        self.timeLeftLabel.pack()

def timeLeft(t):
    time.sleep(1)
    print(t)

def countdownInGUI():
    countdown = Label(root, text=entryInt)
    countdown.pack()

entryInt = IntVar()
t = Entry(root, textvariable=entryInt)
t.bind('<Return>', get)
t.pack(pady=5)

我希望剩余的时间将显示在名为倒数的标签中,但是直到计时器结束之前什么都没有显示,然后每秒在新行上显示“ PY_VAR0”(因此,在3行上显示3秒钟, 4行,以秒为单位,等等。

1 个答案:

答案 0 :(得分:0)

在功能countdownInGUI中,您通过Label创建了Label(root, text=entryInt)小部件,因此tkinter会尝试将传递的内容转换为字符串。您应该做的是将entryInt设置为textvariable

另一方面,您实际上不需要为textvariable小部件设置Entry-您可以通过调用Entry.get()直接检索内容。

这是所有事情都可以根据您的代码工作的方式:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self,master=None,**kwargs):
        super().__init__(master,**kwargs)
        self.master = master
        self.timeLeftLabel = tk.Label(master, text='Time Left: ')
        self.timeLeftLabel.pack()
        self.entryInt = tk.StringVar()
        self.countdown = tk.Label(master, textvariable=self.entryInt)
        self.countdown.pack()
        self.t = tk.Entry(master)
        self.t.bind('<Return>', self.start_countdown)
        self.t.pack(pady=5)

    def start_countdown(self,event=None):
        if self.t.get().isdigit():
            self.time_left(int(self.t.get()))

    def time_left(self, t):
        self.entryInt.set(t)
        t-=1
        if t>=0:
            self.master.after(1000,self.time_left, t)
        else:
            self.entryInt.set("Boom!")

root = tk.Tk()

frame = Application(root)
frame.pack()

root.mainloop()