Tkinter GUI with Countdown in Python

You will learn how to create a simple Tkinter GUI with a countdown timer.

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  Effortlessly Select Files with Tkinter's askopenfilename

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 do you add a button in Python?

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 modify the code to change the countdown time, the text of the label, or the appearance of the window.

See also  Creating Scrollable Interfaces with Tkinter