Introduction
Briefly explain Tkinter as a GUI toolkit for Python.
Introduce the project: A countdown timer with start, pause, and reset functionality.
Setting Up Tkinter
Mention that Tkinter comes pre-installed with Python, so no extra installation is needed.
The Code
from tkinter import *
import time
def start_timer():
global running, time_left
if not running:
running = True
countdown()
def pause_timer():
global running
running = False
def reset_timer():
global running, time_left
running = False
time_left = int(e1.get()) if e1.get().isdigit() else 0
l2.config(text=f"Time Left: {time_left}s")
def countdown():
global time_left
if running and time_left > 0:
time_left -= 1
l2.config(text=f"Time Left: {time_left}s")
b.after(1000, countdown)
# Main Window
b = Tk()
b.title("Simple Timer")
b.geometry("300x200")
running = False
# Input Field for Time
l1 = Label(b, text="Enter Time (seconds):")
l1.pack()
e1 = Entry(b)
e1.pack()
time_left = 0
# Timer Display
l2 = Label(b, text=f"Time Left: {time_left}s", font=("Arial", 14))
l2.pack()
# Buttons
b1 = Button(b, text="Start", command=start_timer)
b1.pack()
b2 = Button(b, text="Pause", command=pause_timer)
b2.pack()
b3 = Button(b, text="Reset", command=reset_timer)
b3.pack()
b.mainloop()
Code Explanation
- Explain each function:
- start_timer(): Starts the countdown.
- pause_timer(): Pauses the countdown.
- reset_timer(): Resets the time to the user’s input.
- countdown(): Decreases the time and updates the label every second.
If you want to know anything about of GUI coding. comment me, follow and subscribe
Top comments (0)