Attempting to make countdown timer with Tkinter

Viewed 394

I am attempting to make a clock using python's Tkinter. It works but not in the way I intended. Once the user enters the amount of time that needs to be counted down from, the action is performed but the actual countdown isn't being shown. I would like for the user to have the ability to watch the numbers go all the way until 0. Any help is greatly appreciated.

import time
from tkinter import *


root = Tk()


def countdown(t):
    ts = int(t)
    while ts > 0:
        timer = Label(timerFrame, text = ts)
        ts-=1
        timer.pack()
        time.sleep(1)
        if ts ==0:
            timer.destroy()
            completeTimer = Label(timerFrame, text="Time is complete")
            completeTimer.pack()


timerFrame = LabelFrame(root, padx=50, pady=50, bd=0)


timerFrameText = Label(timerFrame, 
    text="Enter time in seconds for countdown",
    font=("Arial", 20, "bold")
)
countdownBox= Entry(timerFrame, bd=3)

submitCountdown = Button(timerFrame, 
    padx=5, 
    pady=5, 
    text="Submit", 
    font=("Arial", 20),
    command= lambda:countdown(countdownBox.get())
   )


timerFrame.pack()


timerFrameText.pack()
countdownBox.pack()
submitCountdown.pack()


root.mainloop()
2 Answers

You can try this one I've implemented Threading. This allows you to run threads or let's say processes synchronously. In creating GUI applications and such as timers or any other program that needs to be run all at the same time it's really important that to learn Multithreading and MultiProcessing. It's a really huge factor in software development.

import time
from tkinter import *
import threading
root = Tk()


def cd(timer_label_obj,ts):
    while ts > 0:
        timer_label_obj.config(text=ts)
        ts-=1
        timer_label_obj.pack()
        time.sleep(1)
        if ts ==0:
            timer_label_obj.destroy()
            completeTimer = Label(timerFrame, text="Time is complete")
            completeTimer.pack()

def countdown(t):
    timer = Label(timerFrame)
    ts = int(t)
    th = threading.Thread(target=cd,args=[timer,ts])
    th.start()


timerFrame = LabelFrame(root, padx=50, pady=50, bd=0)


timerFrameText = Label(timerFrame, 
    text="Enter time in seconds for countdown",
    font=("Arial", 20, "bold")
)
countdownBox= Entry(timerFrame, bd=3)


submitCountdown = Button(timerFrame, 
    padx=5, 
    pady=5, 
    text="Submit", 
    font=("Arial", 20),
    command= lambda:countdown(countdownBox.get())
   )




timerFrame.pack()


timerFrameText.pack()
countdownBox.pack()
submitCountdown.pack()


root.mainloop()

Maybe adding some kind of print statement with your ts value will help. Never used tkinter, but it looks like you only print when it finishes count down. Or try to print ts as a string like in a normal print statment:

print("current count %s" %ts)
Related