Simple Stopwatch
Abstract
Simple Stopwatch is a Python GUI application that provides basic stopwatch functionality using Tkinter. The application features a large digital display showing elapsed seconds, along with Start, Stop, and Reset buttons for time control. This project demonstrates GUI development, time handling, event-driven programming, and state management in Python. It’s an excellent introduction to creating interactive desktop applications with real-time updates.
Prerequisites
- Python 3.6 or above
- A code editor or IDE
- tkinter module (usually comes pre-installed)
Before you Start
Before starting this project, you must have Python installed on your computer. If you don’t have Python installed, you can download it from here. You must have a code editor or IDE installed on your computer. If you don’t have any code editor or IDE installed, you can download Visual Studio Code from here.
Note: This project uses only built-in Python modules, so no additional installations are required.
Getting Started
Create a Project
- Create a folder named
simple-stopwatch
simple-stopwatch
. - Open the folder in your favorite code editor or IDE.
- Create a file named
simplestopwatch.py
simplestopwatch.py
. - Copy the given code and paste it in your
simplestopwatch.py
simplestopwatch.py
file.
Write the Code
- Copy and paste the following code in your
simplestopwatch.py
simplestopwatch.py
file.
⚙️ Simple Stopwatch
# Simple Stopwatch
# Import Modules
import time
import datetime
import tkinter as tk
# Defining Variables
root = tk.Tk()
root.title("Simple Stopwatch")
root.geometry("500x500")
root.resizable(False, False)
root.config(bg="black")
# Defining Functions
def start():
global running
running = True
global count
count = -1
counter()
def counter():
global running
global count
if running:
count += 1
time_label.config(text=str(count))
time_label.after(1000, counter)
def stop():
global running
running = False
def reset():
global count
count = 0
time_label.config(text=str(count))
# Creating Widgets
time_label = tk.Label(root, text="0", font=("Helvetica", 80), bg="black", fg="white")
start_button = tk.Button(root, text="Start", font=("Helvetica", 20), bg="black", fg="white", command=start)
stop_button = tk.Button(root, text="Stop", font=("Helvetica", 20), bg="black", fg="white", command=stop)
reset_button = tk.Button(root, text="Reset", font=("Helvetica", 20), bg="black", fg="white", command=reset)
# Placing Widgets
time_label.pack(pady=20)
start_button.pack(pady=20)
stop_button.pack(pady=20)
reset_button.pack(pady=20)
# Calling Functions
root.mainloop()
# Simple Stopwatch
# Import Modules
import time
import datetime
import tkinter as tk
# Defining Variables
root = tk.Tk()
root.title("Simple Stopwatch")
root.geometry("500x500")
root.resizable(False, False)
root.config(bg="black")
# Defining Functions
def start():
global running
running = True
global count
count = -1
counter()
def counter():
global running
global count
if running:
count += 1
time_label.config(text=str(count))
time_label.after(1000, counter)
def stop():
global running
running = False
def reset():
global count
count = 0
time_label.config(text=str(count))
# Creating Widgets
time_label = tk.Label(root, text="0", font=("Helvetica", 80), bg="black", fg="white")
start_button = tk.Button(root, text="Start", font=("Helvetica", 20), bg="black", fg="white", command=start)
stop_button = tk.Button(root, text="Stop", font=("Helvetica", 20), bg="black", fg="white", command=stop)
reset_button = tk.Button(root, text="Reset", font=("Helvetica", 20), bg="black", fg="white", command=reset)
# Placing Widgets
time_label.pack(pady=20)
start_button.pack(pady=20)
stop_button.pack(pady=20)
reset_button.pack(pady=20)
# Calling Functions
root.mainloop()
- Save the file.
- Open the terminal in your code editor or IDE and navigate to the folder
simple-stopwatch
simple-stopwatch
.
C:\Users\Your Name\simple-stopwatch> python simplestopwatch.py
# A GUI window will open with:
# - Large digital time display showing "0"
# - Start button to begin counting
# - Stop button to pause counting
# - Reset button to return to zero
# - Black background with white text for better visibility
C:\Users\Your Name\simple-stopwatch> python simplestopwatch.py
# A GUI window will open with:
# - Large digital time display showing "0"
# - Start button to begin counting
# - Stop button to pause counting
# - Reset button to return to zero
# - Black background with white text for better visibility
Explanation
Code Breakdown
- Import required modules.
import time
import datetime
import tkinter as tk
import time
import datetime
import tkinter as tk
- Set up the main window.
root = tk.Tk()
root.title("Simple Stopwatch")
root.geometry("500x500")
root.resizable(False, False)
root.config(bg="black")
root = tk.Tk()
root.title("Simple Stopwatch")
root.geometry("500x500")
root.resizable(False, False)
root.config(bg="black")
- Define the start function.
def start():
global running
running = True
global count
count = -1
counter()
def start():
global running
running = True
global count
count = -1
counter()
- Implement the counter mechanism.
def counter():
global running
global count
if running:
count += 1
time_label.config(text=str(count))
time_label.after(1000, counter)
def counter():
global running
global count
if running:
count += 1
time_label.config(text=str(count))
time_label.after(1000, counter)
- Define stop and reset functions.
def stop():
global running
running = False
def reset():
global count
count = 0
time_label.config(text=str(count))
def stop():
global running
running = False
def reset():
global count
count = 0
time_label.config(text=str(count))
- Create and place GUI widgets.
time_label = tk.Label(root, text="0", font=("Helvetica", 80), bg="black", fg="white")
start_button = tk.Button(root, text="Start", font=("Helvetica", 20), bg="black", fg="white", command=start)
stop_button = tk.Button(root, text="Stop", font=("Helvetica", 20), bg="black", fg="white", command=stop)
reset_button = tk.Button(root, text="Reset", font=("Helvetica", 20), bg="black", fg="white", command=reset)
time_label.pack(pady=20)
start_button.pack(pady=20)
stop_button.pack(pady=20)
reset_button.pack(pady=20)
time_label = tk.Label(root, text="0", font=("Helvetica", 80), bg="black", fg="white")
start_button = tk.Button(root, text="Start", font=("Helvetica", 20), bg="black", fg="white", command=start)
stop_button = tk.Button(root, text="Stop", font=("Helvetica", 20), bg="black", fg="white", command=stop)
reset_button = tk.Button(root, text="Reset", font=("Helvetica", 20), bg="black", fg="white", command=reset)
time_label.pack(pady=20)
start_button.pack(pady=20)
stop_button.pack(pady=20)
reset_button.pack(pady=20)
Features
- Digital Display: Large, easy-to-read time counter
- Start/Stop Functionality: Control timing with button clicks
- Reset Capability: Return counter to zero instantly
- Clean Interface: Black background with white text for clarity
- Fixed Window Size: Non-resizable window for consistent layout
- Real-time Updates: Counter updates every second automatically
- State Management: Proper handling of running/stopped states
How It Works
State Management
The stopwatch uses global variables to manage its state:
running
running
: Boolean flag indicating if the stopwatch is activecount
count
: Integer storing the current elapsed seconds
Timer Mechanism
The application uses Tkinter’s after()
after()
method for timing:
- Start: Sets
running
running
to True and begins the counter - Counter: Recursively calls itself every 1000ms (1 second)
- Stop: Sets
running
running
to False, breaking the recursive loop - Reset: Sets count back to 0 and updates display
Event Flow
Start Button → running = True → counter() begins
↓
counter() → updates display → schedules next call (1 second)
↓
Stop Button → running = False → counter() stops recurring
↓
Reset Button → count = 0 → display updates to "0"
Start Button → running = True → counter() begins
↓
counter() → updates display → schedules next call (1 second)
↓
Stop Button → running = False → counter() stops recurring
↓
Reset Button → count = 0 → display updates to "0"
GUI Components
Time Display
- Font: Helvetica, size 80 for maximum readability
- Colors: White text on black background
- Position: Centered at the top with padding
Control Buttons
- Start Button: Begins or resumes timing
- Stop Button: Pauses timing (can be resumed)
- Reset Button: Resets counter to zero
- Styling: Consistent black/white theme
Use Cases
- Exercise Timing: Track workout durations
- Study Sessions: Monitor focused work periods
- Cooking: Time preparation and cooking processes
- Presentations: Keep track of speaking time
- General Timing: Any activity requiring time measurement
Next Steps
You can enhance this project by:
- Adding millisecond precision for more accurate timing
- Implementing lap time functionality
- Adding sound alerts at specific intervals
- Creating multiple simultaneous timers
- Adding time formatting (MM or HH:MM)
- Implementing countdown timer mode
- Adding keyboard shortcuts for controls
- Creating customizable themes and colors
- Adding time logging and history features
- Implementing export functionality for recorded times
Enhanced Version Ideas
def enhanced_stopwatch():
# Features to add:
# - Lap time recording
# - Multiple time formats
# - Sound notifications
# - Customizable themes
# - Keyboard shortcuts
# - Time export functionality
pass
def format_time(seconds):
# Convert seconds to HH:MM:SS format
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
def enhanced_stopwatch():
# Features to add:
# - Lap time recording
# - Multiple time formats
# - Sound notifications
# - Customizable themes
# - Keyboard shortcuts
# - Time export functionality
pass
def format_time(seconds):
# Convert seconds to HH:MM:SS format
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
Advanced Features Ideas
Lap Time Functionality
def add_lap():
global count
lap_times.append(count)
update_lap_display()
def show_lap_times():
# Display list of recorded lap times
pass
def add_lap():
global count
lap_times.append(count)
update_lap_display()
def show_lap_times():
# Display list of recorded lap times
pass
Time Formatting
def format_display(seconds):
if seconds < 60:
return f"{seconds}s"
elif seconds < 3600:
minutes = seconds // 60
secs = seconds % 60
return f"{minutes:02d}:{secs:02d}"
else:
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
def format_display(seconds):
if seconds < 60:
return f"{seconds}s"
elif seconds < 3600:
minutes = seconds // 60
secs = seconds % 60
return f"{minutes:02d}:{secs:02d}"
else:
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
Performance Considerations
- Memory Usage: Minimal memory footprint with simple variables
- CPU Usage: Low impact with 1-second intervals
- GUI Responsiveness: Non-blocking timer implementation
- Accuracy: Good for general timing (±1 second precision)
Educational Value
This project teaches:
- GUI Development: Creating interactive desktop applications
- Event Handling: Responding to button clicks and timer events
- State Management: Managing application state with global variables
- Timer Programming: Using
after()
after()
for scheduled updates - Layout Management: Organizing GUI components with pack()
Common Improvements
- Precision: Use
time.time()
time.time()
for sub-second accuracy - Visual Feedback: Add color changes for different states
- User Experience: Add confirmation dialogs for reset
- Accessibility: Implement keyboard navigation
- Persistence: Save timing sessions to files
Real-World Applications
- Sports Training: Track exercise and rest intervals
- Productivity: Implement Pomodoro technique timing
- Education: Time quiz sessions and study periods
- Professional: Track billable work hours
- Entertainment: Game timing and challenges
Troubleshooting Tips
- Timer Not Starting: Check if
running
running
variable is properly set - Display Not Updating: Ensure
after()
after()
method is called correctly - Button Responsiveness: Verify command functions are properly defined
- Window Issues: Check geometry and resizable settings
Conclusion
In this project, we learned how to create a Simple Stopwatch using Python’s Tkinter library. We explored GUI development concepts including event handling, timer programming, and state management. This project demonstrates how to create responsive, real-time applications with clean user interfaces. The stopwatch serves as an excellent foundation for understanding time-based applications and can be extended with many additional features. To find more projects like this, you can visit Python Central Hub.
Was this page helpful?
Let us know how we did