Python
Python

 

Introduction

A stopwatch is a useful tool for measuring the passage of time. In this guide, we will walk you through creating a simple stopwatch using the Python programming language. The program will allow users to start, stop, and reset the stopwatch, with a graphical user interface (GUI) to enhance user experience.

Objective

The objective of this program is to create a simple yet functional stopwatch application that can display elapsed time, start, stop, and reset the timer. By the end of this guide, you will be able to understand basic Python programming concepts and how to integrate them into building a GUI-based stopwatch.

Code

import tkinter as tk
import time

# Stopwatch class definition
class Stopwatch:
    def __init__(self, root):
        self.root = root
        self.root.title("Stopwatch")
        
        self.start_time = 0
        self.running = False
        self.elapsed_time = 0

        # Label to display time
        self.time_display = tk.Label(self.root, text="0.00", font=("Helvetica", 48))
        self.time_display.pack()

        # Start/Stop button
        self.start_stop_button = tk.Button(self.root, text="Start", width=10, command=self.toggle)
        self.start_stop_button.pack()

        # Reset button
        self.reset_button = tk.Button(self.root, text="Reset", width=10, command=self.reset)
        self.reset_button.pack()

        # Update function to refresh time display
        self.update()

    def toggle(self):
        """Start or stop the stopwatch."""
        if self.running:
            self.elapsed_time += time.time() - self.start_time
            self.running = False
            self.start_stop_button.config(text="Start")
        else:
            self.start_time = time.time()
            self.running = True
            self.start_stop_button.config(text="Stop")

    def reset(self):
        """Reset the stopwatch."""
        self.elapsed_time = 0
        self.time_display.config(text="0.00")

    def update(self):
        """Update the stopwatch display every 100 ms."""
        if self.running:
            elapsed = self.elapsed_time + (time.time() - self.start_time)
            self.time_display.config(text=f"{elapsed:.2f}")
        self.root.after(100, self.update)

# Main program to run the stopwatch
if __name__ == "__main__":
    root = tk.Tk()
    stopwatch = Stopwatch(root)
    root.mainloop()

Explanation of Program Structure

The program uses the tkinter library to create the graphical user interface (GUI). Here’s a breakdown of the program:

  • Stopwatch class: The class Stopwatch manages the entire stopwatch’s functionality, including the display and interaction with the buttons.
  • Time Calculation: The stopwatch tracks the time using the time.time() function, which provides the current time in seconds. The time is calculated and displayed by the update() function, which runs every 100 milliseconds.
  • Start/Stop Button: The toggle() function is used to start or stop the stopwatch. When the stopwatch is running, the button’s text changes from “Start” to “Stop”.
  • Reset Button: The reset() function resets the stopwatch to zero and updates the display.
  • Main Program: The root object is the main window, and an instance of the Stopwatch class is created. The program runs the main event loop using root.mainloop().

How to Run the Program

Follow these steps to run the program:

  1. Ensure you have Python installed on your system. You can download it from python.org.
  2. Install the tkinter library (if not already installed) by running pip install tk in the command line or terminal.
  3. Create a new Python file (e.g., stopwatch.py) and copy the provided code into it.
  4. Run the Python file in your terminal or code editor.
  5. The stopwatch window should appear, allowing you to start, stop, and reset the timer.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)