Search code examples
pythontkintertimer

How can I display the current time left in a timer in a label?


I made a timer for part of a project I am making. I have the timer made, but I would like for the time left in the timer to be printed on to a label. ALso, if this wasn't expected, I would like for the time to be on the label then after a second it deletes itself and places the new time remaining(I do not want it to keep printing the time on a new line one after another).

One post I found that was pretty much what I wanted to do, but it did not work for me and I had to change some functions and add some new ones. I am not sure why this didn't work, but I would prefer it to be different because it has a preset time of 10 seconds and I would like for it to be the users choice. The link: 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)

I am hoping that the time left will show in the label called countdown, but instead nothing shows up until the timer ends then it says "PY_VAR0" on a new line for each second (So its on 3 lines for 3 seconds, 4 lines for seconds, etc..)


Solution

  • In your func countdownInGUI, you created your Label widget by Label(root, text=entryInt), so tkinter will try to convert what you passed to a string. What you should do is to set entryInt as a textvariable instead.

    On the other hand, you don't really need to set a textvariable for your Entry widget - you can retrieve the content directly by calling Entry.get().

    Here is how everything could work base on your code:

    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()