In this article, you will learn how to create a simple Tkinter GUI with a countdown timer.
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.
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.
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.
In this article, 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.
FAQ
- Q: How can I change the countdown time?
- A: You can change the value of the `countdown` variable.
- Q: How can I change the text of the label?
- A: You can change the value of the `txt` variable.
- Q: How can I change the appearance of the window?
- A: You can change the properties of the `root` object.