How to make a Stopwatch GUI in Python Tkinter

How to create stopwatch python tkinter

Another Python project. Welcome to this tutorial where we will be exploring how to make a simple stopwatch using Python’s Tkinter library. It’s easy to create a stopwatch GUI application using Python, and we’ll explore how to use Tkinter to create one. Let’s get started!

Application Rule

A stopwatch application is a program that allows a user to start, stop, and reset a timer. The timer begins counting up from zero when the user starts it. It can be stopped and reset to zero at any time. The stopwatch may also have additional features, such as the ability to lap the timer or to save and recall past timer readings.

Typically, a stopwatch application will have a user interface with buttons or other controls that allow the user to start, stop, and reset the timer, as well as access any additional features. The timer is typically displayed in a digital format, showing the elapsed time in seconds, minutes, and possibly even hours.

In this tutorial, we will not implement any additional features. We will just make a basic stopwatch where the timer will display elapsed time only in seconds.

Types of Stopwatch

There are mainly two types of digital stopwatch:

  1. Count-down Stopwatch: This type of digital stopwatch allows the user to set a specific amount of time and counts down until zero. A good example of this kind of stopwatch is an alarm clock which may be useful for boiling something for a specific time while cooking.
  2. Cout Up Stopwatch: It measures the elapsed time from when it is started to when it is stopped. Unlike the countdown stopwatch, it starts from zero. In this tutorial, we will be making this kind of stopwatch project. This type of stopwatch is used in running competitions to measure the time taken to complete a certain track.

Building Blocks

In this tutorial, I will show you how to make a simple stopwatch. To build this simple stopwatch using Python and Tkinter, we will follow the building blocks listed below:

  • A user interface: We will need to design the layout and appearance of your stopwatch using Tkinter widgets such as buttons, labels, and text fields
  • Event handling: Set up event handlers to respond to user input and start, stop, and reset the stopwatch timer. by clicking that particular button
  • Timing functions: You will need to use Python’s time module to measure and update the elapsed time of the stopwatch
  • Displaying results: Need to use Tkinter widgets or functions (Label) to display the elapsed time of the stopwatch to the user
Also Read:  Upload and display image in Flask Python

Also Read:

Create a Stopwatch using Python and Tkinter

Now let’s start coding our simple windows stopwatch in Python with the Tkinter library. I will break the entire code into some steps to explain you better.

1. Import Required Libraries

To make our basic stopwatch, we need three libraries. Tkinter, time and PIL ()

  • Tkinter: To make a windows Application (main library)
  • time: To work with time in Python
  • PIL: To deal with images
import tkinter as tk
import time
from PIL import Image, ImageTk

2. Define Functions

In this section, we need to write all the required functions to make our stopwatch actionable.

  • start() function: This function will activate when we will click the start button
  • stop() function: Function to stop the timer
  • update_time() function: Calculate the time difference and update it continuously
# Start the stopwatch
def start():
    global is_running
    global start_time
    if not is_running:
        is_running = True
        start_time = time.time()
        update_time()

# Stop the stopwatch
def stop():
    global is_running
    is_running = False

# Update the elapsed time
def update_time():
    if is_running:
        elapsed_time = time.time() - start_time
        time_label.config(text="{:.2f}".format(elapsed_time))
        time_label.after(50, update_time)

3. Setup Application Window

In this tutorial, we will be setting the dimensions of our stopwatch application window to 350 pixels in width and 400 pixels in height.

# Create the main window
window = tk.Tk()
# # Specify screen size of the Application window
window.geometry('350x400')
# # Specify application name
window.title("Stopwatch")

4. Setup Application Background

In this section, I will use a stopwatch image as a background for our application. This is to make our stopwatch stylish. If you just want to understand the basic functionality of a stopwatch, you can skip this step.

Also Read:  Best Udemy Courses to learn Django with Learning Path

I used canva to make below background image for my stopwatch. You just need to create a project in canva with custom size (width: 350 and height: 400 – as per our application window size).

stopwatch python
Background image
# Read image using PIL library
im = Image.open('stopwatch.png')
# Convert image to tkinter format
bg = ImageTk.PhotoImage(im)
# Display image as application background
img = tk.Label(window, image=bg)
img.place(x=0, y=0)

5. Add Widgets

Now we need to add all the required widgets to make a graphical interface for our Stopwatch app. Here are the list of widgets:

  • Label: To display the elapsed time
  • Start Button: To reset and start the timer. This button will call start() function
  • Stop Button: To stop the timer. This button will work as stop() function
# Create the label to display the elapsed time
time_label = tk.Label(window, text="0.00", font=("Helvetica", 48))
time_label.place(x=110, y=190)

# Create the start and stop buttons
start_button = tk.Button(window, text="Start", width=10, command=start)
start_button.place(x=10, y=10)
stop_button = tk.Button(window, text="Stop", width=10, command=stop)
stop_button.place(x=260, y=10)

# Flag to track whether the stopwatch is running
is_running = False

Here I am placing the Buttons on top of the timer image and Label at the stomach of the stopwatch image.

My idea is to show the timer label at the center of this stopwatch image so that it would look more realistic. This is just for fun. You can try something else.

6. Run mainloop()

At this point, we are done with our python code for the stopwatch GUI. All that is left to do is to execute the mainloop() method to launch the application.

# Run the main loop
window.mainloop()

That’s it. You successfully created a stopwatch in python using the Tkinter library, which should be up and running in your windows system right now.

python stopwatch using tkinter gui
Final Output GUI of Stopwatch

Stopwatch source code in Python – Full Code

In the above sections, I have provided a detailed explanation of how to create a Python stopwatch GUI project. Let me now compile all the steps and present the final code for your reference.

import tkinter as tk
import time
from PIL import Image, ImageTk

# Start the stopwatch
def start():
    global is_running
    global start_time
    if not is_running:
        is_running = True
        start_time = time.time()
        update_time()

# Stop the stopwatch
def stop():
    global is_running
    is_running = False

# Update the elapsed time
def update_time():
    if is_running:
        elapsed_time = time.time() - start_time
        time_label.config(text="{:.2f}".format(elapsed_time))
        time_label.after(50, update_time)

# Create the main window
window = tk.Tk()
# # Specify screen size of the Application window
window.geometry('350x400')
# # Specify application name
window.title("Stopwatch")
# window.config(bg='#299617')

# Read image using PIL library
im = Image.open('stopwatch.png')
# Convert image to tkinter format
bg = ImageTk.PhotoImage(im)
# Display image as application background
img = tk.Label(window, image=bg)
img.place(x=0, y=0)

# Create the label to display the elapsed time
time_label = tk.Label(window, text="0.00", font=("Helvetica", 48))
time_label.place(x=110, y=190)

# Create the start and stop buttons
start_button = tk.Button(window, text="Start", width=10, command=start)
start_button.place(x=10, y=10)
stop_button = tk.Button(window, text="Stop", width=10, command=stop)
stop_button.place(x=260, y=10)

# Flag to track whether the stopwatch is running
is_running = False

# Run the main loop
window.mainloop()

End Note

Creating a stopwatch GUI in Python Tkinter is an easy process that requires basic knowledge of Python programming and Tkinter library functions. With a few lines of code, you can create a visually appealing and functional stopwatch that can be used for various purposes.

Also Read:  How to Create Desktop Application Using Python

Whether you are a beginner or an experienced Python developer, this tutorial provides a useful guide for creating a stopwatch GUI project that meets your needs.

That’s it. If you have any questions or suggestions regarding this tutorial, please let me know in the comment section below.

Similar Read:

Leave a comment