How to Create a Tkinter GUI Countdown Timer in Python (Simple Counter Example)

You will learn how to create a simple Tkinter GUI countdown timer in Python that updates a label on the screen as the counter runs.

counter 3

counter

counter 1

counter done

The Python Code

This is the code of tkinter countdown timer visible above.

import tkinter, time

root = tkinter.Tk()
root.title("Counter GUI")
countdown = 4
txt = "Counter "
bg = tkinter.Label(master=root, bg="black", fg="white", font="Arial 70", text="{0}{1}".format(txt, str(countdown)))
bg.pack()


def starting(ev):
    global txt, countdown
    if ev == "Enter":
        while countdown != 0:
            time.sleep(0.5)
            countdown -= 1
            bg["text"] = txt + str(countdown)
            bg.update()
            time.sleep(1)
        bg["text"] = "Done!"


root.bind("Space", starting(ev="Enter"))
root.mainloop()

The first line imports the tkinter and time modules. The tkinter module is used to create graphical user interfaces, and the time module is used to manage time.

See also  Tkinter Python GUI Tutorial: Complete Guide with Code Examples

The next few lines create a Tkinter window and a label. The label is used to display the countdown timer.

The starting() function is used to start the countdown timer. The function takes an event as an argument. In this case, the event is the Space key being pressed.

The while loop in the starting() function decrements the countdown variable and updates the label text. The time.sleep() function pauses the execution of the code for the specified amount of time.

See also  How to Draw a Hyperbola with Asymptotes in Python Tkinter Canvas

The root.bind() method binds the Space key to the starting() function. This means that when the Space key is pressed, the starting() function will be called.

The root.mainloop() method keeps the window open until the user closes it.

You learned how to create a simple Tkinter GUI with a countdown timer. You can easily customize this Python Tkinter countdown timer code to change the starting time, label text, font, and window appearance for different desktop timer use cases.

See also  How to use widgets to process text input in Tkinter applications