Here's a Python script using Tkinter to create a simple GUI with both a functioning timer and a stopwatch.
Features:
Stopwatch: Start, Stop, Reset, counts up in seconds.
Timer: Set duration (in seconds), Start, Stop, Reset, counts down.
Separate controls and displays for clarity.
python
import tkinter as tk
from tkinter import ttk, messagebox
import datetime
class TimerStopwatchApp:
def __init__(self, master):
self.master = master
master.title("Timer & Stopwatch")
master.geometry("400x500") # Set initial window size
master.resizable(False, False) # Make window non-resizable
# --- Styles ---
self.style = ttk.Style()
self.style.configure("TFrame", background="#f0f0f0")
self.style.configure("TLabel", background="#f0f0f0", font=("Helvetica", 14))
self.style.configure("Time.TLabel", font=("Helvetica", 24, "bold"), foreground="#333333")
self.style.configure("TButton", font=("Helvetica", 10), padding=5)
self.style.configure("Run.TLabel", font=("Helvetica", 24, "bold"), foreground="green")
self.style.configure("Stop.TLabel", font=("Helvetica", 24, "bold"), foreground="red")
# --- Stopwatch Variables ---
self.stopwatch_running = False
self.stopwatch_seconds = 0
self.stopwatch_after_id = None
# --- Timer Variables ---
self.timer_running = False
self.timer_seconds_left = 0
self.initial_timer_seconds = 0 # To store the value for reset
self.timer_after_id = None
self.create_widgets()
def create_widgets(self):
# --- Stopwatch Section ---
stopwatch_frame = ttk.LabelFrame(self.master, text="Stopwatch", padding="10 10 10 10")
stopwatch_frame.pack(pady=20, padx=20, fill="x")
self.stopwatch_display = ttk.Label(stopwatch_frame, text="00:00:00", style="Time.TLabel")
self.stopwatch_display.pack(pady=10)
stopwatch_buttons_frame = ttk.Frame(stopwatch_frame)
stopwatch_buttons_frame.pack(pady=5)
self.btn_stopwatch_start = ttk.Button(stopwatch_buttons_frame, text="Start", command=self.start_stopwatch)
self.btn_stopwatch_start.grid(row=0, column=0, padx=5)
self.btn_stopwatch_stop = ttk.Button(stopwatch_buttons_frame, text="Stop", command=self.stop_stopwatch, state=tk.DISABLED)
self.btn_stopwatch_stop.grid(row=0, column=1, padx=5)
self.btn_stopwatch_reset = ttk.Button(stopwatch_buttons_frame, text="Reset", command=self.reset_stopwatch)
self.btn_stopwatch_reset.grid(row=0, column=2, padx=5)
# --- Timer Section ---
timer_frame = ttk.LabelFrame(self.master, text="Timer", padding="10 10 10 10")
timer_frame.pack(pady=20, padx=20, fill="x")
timer_input_frame = ttk.Frame(timer_frame)
timer_input_frame.pack(pady=5)
ttk.Label(timer_input_frame, text="Set Time (seconds):").grid(row=0, column=0, padx=5)
self.timer_input = ttk.Entry(timer_input_frame, width=10, font=("Helvetica", 12))
self.timer_input.insert(0, "60") # Default to 60 seconds
self.timer_input.grid(row=0, column=1, padx=5)
self.timer_input.bind("<Return>", lambda e: self.set_timer_duration()) # Bind Enter key
self.btn_set_timer = ttk.Button(timer_input_frame, text="Set", command=self.set_timer_duration)
self.btn_set_timer.grid(row=0, column=2, padx=5)
self.timer_display = ttk.Label(timer_frame, text="00:00:00", style="Time.TLabel")
self.timer_display.pack(pady=10)
timer_buttons_frame = ttk.Frame(timer_frame)
timer_buttons_frame.pack(pady=5)
self.btn_timer_start = ttk.Button(timer_buttons_frame, text="Start", command=self.start_timer)
self.btn_timer_start.grid(row=0, column=0, padx=5)
self.btn_timer_stop = ttk.Button(timer_buttons_frame, text="Stop", command=self.stop_timer, state=tk.DISABLED)
self.btn_timer_stop.grid(row=0, column=1, padx=5)
self.btn_timer_reset = ttk.Button(timer_buttons_frame, text="Reset", command=self.reset_timer)
self.btn_timer_reset.grid(row=0, column=2, padx=5)
# Initial display update for timer
self.set_timer_duration(initial=True)
# --- Stopwatch Functions ---
def update_stopwatch(self):
if self.stopwatch_running:
self.stopwatch_seconds += 1
time_str = str(datetime.timedelta(seconds=self.stopwatch_seconds))
self.stopwatch_display.config(text=time_str, style="Run.TLabel")
self.stopwatch_after_id = self.master.after(1000, self.update_stopwatch)
def start_stopwatch(self):
if not self.stopwatch_running:
self.stopwatch_running = True
self.btn_stopwatch_start.config(state=tk.DISABLED)
self.btn_stopwatch_stop.config(state=tk.NORMAL)
self.update_stopwatch()
def stop_stopwatch(self):
if self.stopwatch_running:
self.stopwatch_running = False
if self.stopwatch_after_id:
self.master.after_cancel(self.stopwatch_after_id)
self.btn_stopwatch_start.config(state=tk.NORMAL)
self.btn_stopwatch_stop.config(state=tk.DISABLED)
self.stopwatch_display.config(style="Stop.TLabel") # Change color when stopped
def reset_stopwatch(self):
self.stop_stopwatch() # Stop if running
self.stopwatch_seconds = 0
self.stopwatch_display.config(text="00:00:00", style="Time.TLabel") # Reset color
# --- Timer Functions ---
def set_timer_duration(self, initial=False):
if self.timer_running:
messagebox.showwarning("Timer Running", "Please stop the timer before setting a new duration.")
return
try:
seconds_input = int(self.timer_input.get())
if seconds_input <= 0:
raise ValueError
self.initial_timer_seconds = seconds_input
self.timer_seconds_left = seconds_input
time_str = str(datetime.timedelta(seconds=self.timer_seconds_left))
self.timer_display.config(text=time_str, style="Time.TLabel")
self.btn_timer_start.config(state=tk.NORMAL)
except ValueError:
if not initial: # Don't show error on initial load if default is wrong
messagebox.showerror("Invalid Input", "Please enter a valid positive number for seconds.")
self.timer_input.delete(0, tk.END)
self.timer_input.insert(0, "0") # Clear invalid input
self.timer_seconds_left = 0
self.initial_timer_seconds = 0
self.timer_display.config(text="00:00:00", style="Time.TLabel")
self.btn_timer_start.config(state=tk.DISABLED)
def update_timer(self):
if self.timer_running:
if self.timer_seconds_left > 0:
self.timer_seconds_left -= 1
time_str = str(datetime.timedelta(seconds=self.timer_seconds_left))
self.timer_display.config(text=time_str, style="Run.TLabel")
self.timer_after_id = self.master.after(1000, self.update_timer)
else:
self.stop_timer() # Timer reached 0
self.timer_display.config(text="TIME'S UP!", style="Stop.TLabel")
messagebox.showinfo("Timer", "Time's up!")
def start_timer(self):
if not self.timer_running and self.timer_seconds_left > 0:
self.timer_running = True
self.btn_timer_start.config(state=tk.DISABLED)
self.btn_timer_stop.config(state=tk.NORMAL)
self.btn_set_timer.config(state=tk.DISABLED)
self.timer_input.config(state=tk.DISABLED)
self.update_timer()
elif self.timer_seconds_left == 0:
messagebox.showwarning("Timer", "Please set a duration for the timer.")
def stop_timer(self):
if self.timer_running:
self.timer_running = False
if self.timer_after_id:
self.master.after_cancel(self.timer_after_id)
self.btn_timer_start.config(state=tk.NORMAL)
self.btn_timer_stop.config(state=tk.DISABLED)
self.btn_set_timer.config(state=tk.NORMAL)
self.timer_input.config(state=tk.NORMAL)
self.timer_display.config(style="Stop.TLabel") # Change color when stopped
def reset_timer(self):
self.stop_timer() # Stop if running
self.timer_seconds_left = self.initial_timer_seconds
time_str = str(datetime.timedelta(seconds=self.timer_seconds_left))
self.timer_display.config(text=time_str, style="Time.TLabel")
self.btn_timer_start.config(state=tk.NORMAL if self.initial_timer_seconds > 0 else tk.DISABLED)
# --- Main Application Loop ---
if __name__ == "__main__":
root = tk.Tk()
app = TimerStopwatchApp(root)
root.mainloop()
How to Use:
Save: Save the code as a Python file (e.g., timer_stopwatch.py).
Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run: python timer_stopwatch.py
Explanation:
tkinter: The standard Python GUI library.
ttk: Tkinter's themed widgets, which give a more modern look and feel.
datetime: Used to easily format seconds into HH:MM:SS strings.
TimerStopwatchApp Class: Encapsulates all the GUI elements and logic.
__init__: Initializes the main window, sets up styles, and initializes variables for both the stopwatch and timer.
create_widgets: Defines and places all the buttons, labels, and entry fields using ttk.LabelFrame, ttk.Label, ttk.Button, ttk.Entry, and ttk.Frame for grouping. It uses pack() for general layout and grid() within button frames for alignment.
stopwatch_running / timer_running: Boolean flags to track if the respective function is active.
stopwatch_seconds / timer_seconds_left: Integers to store the current time in seconds.
stopwatch_after_id / timer_after_id: These store the ID returned by master.after(). This ID is crucial for being able to cancel a scheduled function call later.
update_stopwatch / update_timer: These are the core functions that increment/decrement the time and update the display. They use self.master.after(1000, self.update_...) to schedule themselves to run again after 1000 milliseconds (1 second).
start_..., stop_..., reset_...: Functions linked to the buttons that control the state and behavior of the stopwatch/timer. They also handle enabling/disabling buttons as appropriate.
set_timer_duration: Parses the input from the Entry widget, converts it to an integer (seconds), and sets the initial timer value. Includes basic error handling for non-numeric input.
Styling (ttk.Style): Adds some basic styling to make the app look a bit cleaner, including changing text size and color when running/stopped.