Build a Simple Stopwatch using Python

Simple Stopwatch using Python

Have you ever needed a stopwatch to time your workouts, cooking sessions, or coding challenges?

In this article, we will build a simple yet functional stopwatch using Python and CustomTkinter, a modern, customizable UI toolkit for Python.

By the end, you’ll have a working stopwatch application that you can use and even enhance further.

Importing Required Libraries

Let’s start by importing the necessary libraries:

  • datetime to handle time-related tasks and
  • customtkinter for the UI.

Initialize the Main Application Window

Create the main application window and set its properties like title and size:

class StopwatchApp(CTk):
    def __init__(self):
        super().__init__()
        
        self.title("Stopwatch")
        self.geometry("400x250")
        self.configure(bg_color="white")
        
        self.running = False
        self.start_time = 0
        self.elapsed_time = 0
        
        self.create_widgets()

    def create_widgets(self):
        # Timer display label
        self.timer_label = CTkLabel(self, text="00:00:00", font=("Helvetica", 40))
        self.timer_label.pack(pady=20)
        
        # Start button
        self.start_button = CTkButton(self, text="Start", command=self.start_timer)
        self.start_button.pack(side="left", padx=10, pady=20)
        
        # Stop button
        self.stop_button = CTkButton(self, text="Stop", command=self.stop_timer)
        self.stop_button.pack(side="left", padx=10, pady=20)
        
        # Reset button
        self.reset_button = CTkButton(self, text="Reset", command=self.reset_timer)
        self.reset_button.pack(side="left", padx=10, pady=20)

Implement the Stopwatch Logic

Next, let’s add the logic for the stopwatch. We’ll create methods to start, stop, and reset the timer:

    def start_timer(self):
        if not self.running:
            self.running = True
            self.start_time = time.time() - self.elapsed_time
            self.update_timer()
    
    def stop_timer(self):
        if self.running:
            self.running = False
            self.elapsed_time = time.time() - self.start_time
    
    def reset_timer(self):
        self.running = False
        self.elapsed_time = 0
        self.timer_label.config(text="00:00:00")
        
    def update_timer(self):
        if self.running:
            self.elapsed_time = time.time() - self.start_time
            minutes, seconds = divmod(self.elapsed_time, 60)
            milliseconds = int((self.elapsed_time % 1) * 100)
            timer_text = f"{int(minutes):02}:{int(seconds):02}:{milliseconds:02}"
            self.timer_label.config(text=timer_text)
            # Call update_timer every 10 milliseconds
            self.after(10, self.update_timer)

Running the Application

Finally, we need to create an instance of our StopwatchApp and start the main event loop:

if __name__ == "__main__":
    app = StopwatchApp()
    app.mainloop()

Full Source Code: Simple Stopwatch using Python

Click For the Full Code of a Simple Stopwatch using Python
from customtkinter import *
import time

class StopwatchApp(CTk):
    def __init__(self):
        super().__init__()
        
        self.title("Stopwatch")
        self.geometry("400x250")
        self.configure(bg_color="white")
        
        self.running = False
        self.start_time = 0
        self.elapsed_time = 0
        
        self.create_widgets()

    def create_widgets(self):
        # Timer display label
        self.timer_label = CTkLabel(self, text="00:00:00", font=("Helvetica", 40))
        self.timer_label.pack(pady=20)
        
        # Start button
        self.start_button = CTkButton(self, text="Start", command=self.start_timer)
        self.start_button.pack(side="left", padx=10, pady=20)
        
        # Stop button
        self.stop_button = CTkButton(self, text="Stop", command=self.stop_timer)
        self.stop_button.pack(side="left", padx=10, pady=20)
        
        # Reset button
        self.reset_button = CTkButton(self, text="Reset", command=self.reset_timer)
        self.reset_button.pack(side="left", padx=10, pady=20)

    def start_timer(self):
        if not self.running:
            self.running = True
            self.start_time = time.time() - self.elapsed_time
            self.update_timer()
    
    def stop_timer(self):
        if self.running:
            self.running = False
            self.elapsed_time = time.time() - self.start_time
    
    def reset_timer(self):
        self.running = False
        self.elapsed_time = 0
        self.timer_label.configure(text="00:00:00")
        
    def update_timer(self):
        if self.running:
            self.elapsed_time = time.time() - self.start_time
            minutes, seconds = divmod(self.elapsed_time, 60)
            milliseconds = int((self.elapsed_time % 1) * 100)
            timer_text = f"{int(minutes):02}:{int(seconds):02}:{milliseconds:02}"
            self.timer_label.configure(text=timer_text)
            # Call update_timer every 10 milliseconds
            self.after(10, self.update_timer)

if __name__ == "__main__":
    app = StopwatchApp()
    app.mainloop()

Challenge 🧗

Now that you’ve built a basic stopwatch, let’s take it a step further with a mini-challenge. Try adding one or more of the following features to enhance your stopwatch:

  1. Lap Timer: Add a button to record lap times. Every time you click the “Lap” button, it should display the current elapsed time in a list below the stopwatch.
  2. Save and Load Sessions: Implement functionality to save the elapsed time or lap times to a file. Add another feature to load and display these times in the stopwatch app.
  3. Sound Alert: Play a sound when the timer stops or when the countdown reaches zero. You can use the pygame or winsound module for this.
  4. Custom Styling: Experiment with CustomTkinter‘s styling options to change the appearance of the stopwatch. Try adding custom colors, fonts, or even animations!

Simple Stopwatch using Python Simple Stopwatch using Python Simple Stopwatch using Python Simple Stopwatch using Python

Leave a Reply

This Post Has One Comment

  1. kevin

    Very nice, a usefull peice of code.