Python Tkinter Stopwatch

In this tutorial, we will learn how to create a simple stopwatch using Python tkinter. We’ll build a basic GUI with start, stop, and reset buttons to track a real Python GUI application.

Let’s begin.

Stopwatch

  • The stopwatch is a simple counting of numbers.
  • It is timed in seconds & helps the user to understand how much time he/she took to complete the task.
  • Later, these deviations in time are analyzed & further plans are set.
  • No competition is possible without a stopwatch.

Overview of Stopwatch in Python

  • The stopwatch can be of two types:
    • Forward counting
    • backward counting
  • Forward-counting stopwatch keeps on increasing till infinite seconds if reset or stop is not pressed.
  • Backward Stopwatch is provided with a number & it moves in the decreasing order until it becomes zero.
  • Backward Stopwatch is also called Countdown watch.
  • We Separate post for Countdown watch.
  • In this section, we will talk about forwarding stopwatch.
  • Stopwatch has StartStop Reset options.
  • Start button starts or resumes the count on the display
  • Stop button stops the count then & there.
  • Reset button sets the timer back to 0 or the starting point.

Read Create Tables in Python Tkinter

Stopwatch source code in Python

In this section, we will explain the easy way to code a stopwatch in Python. It is recommended to please go throw the entire blog.

Step 1:

Import everything from the tkinter module

from tkinter import *

Step 2:

Configure the Main application window

ws = Tk()
ws.geometry('400x450+1000+300')
ws.title('PythonGuides: Stopwatch')
ws.config(bg='#299617')
ws.iconbitmap('stopwatch.ico')
ws.resizable(0,0)
  • The main application window is created & named as ws, which is the shorthand for workspace.
  • Geometry includes the size & position of the window.
    • Here, 400 is the width of the main application.
    • 450 is the height of the main application.
    • 1000 is the x position of the main application.
    • 300 is the y position of the main application.
  • The title is the text appearing on the top of the main application window.
  • ws.config(bg=’colorname or hex code’) this code is used to set the background colour of the main application.
  • iconbitmap is used to set the icon on the main application window. The default icon is a feature.
  • resizable determines the amount window that can be stretched by the user.
    • It accepts x and y values
    • In this case value is 0, 0, which means the window can’t be resized.

Step 3: Place an image of a Stopwatch

bg = PhotoImage(file='stopwatch.png')
img = Label(ws, image=bg, bg='#299617')
img.place(x=75, y=50)
  • We have created an image using logomakr.com
  • bg stores the image that is obtained using PhotoImage
  • The image is placed on the Label using the image option
  • Refer to our label section to know more about the Label.

Step 4:

Placing buttons on the main application window.

start_btn=Button(
    ws, 
    text='Start', 
    width=15, 
    command=lambda:StartTimer(lbl)
    )

start_btn.place(x=30, y=390)
  • Buttons are meant to perform an action
  • To understand the button, please refer to our button section
  • Here, we will look at the command option, the command is the action that will be performed when the button is clicked.
  • We have created an independent function for start, stop & reset that takes a parameter.
  • In the button using the command keyword, we can pass the function, but the catch is that we cannot pass a parameter to that function. So to do that, we use the anonymous function lambda.

Step 5:

Creating Global Variables

counter = -1
running = False
  • Python Variables used in a function are limited to that function only
  • If we want to use a particular variable in another function, then we have to declare that variable as a global variable.
  • In this stopwatch source code in Python, we have declared counter & running as global variables.
  • Any function referring to these variables must use the global keyword before the variable name
  • These two variables are later used in multiple functions.
  • Changes made by any function on these variables will be observed by other functions too.
  • For example, if any function sets the value of the counter to 10, then other functions using the counter will also have the counter value as 10.

Step 6:

Explaining functions

  • counter_label() and count()
def counter_label(lbl):
    def count():
        if running:
            global counter
            if counter==-1:             
                display="00"
            else:
                display=str(counter)

            lbl['text']=display    
            
            lbl.after(1000, count)    
            counter += 1
    count()   
  • In this code, the counter_label is accepting the argument label.
  • count() is another function passed in counter_label.
  • if running means if running == True, below program under the if statement will work till the time running is true.
  • The counting of the number will stop when running is set to false
  • Global counter, here we are calling the variable counter, which is outside this function.
  • Till the time counter is -1, it will display 00 on the screen.
  • The moment the user clicks on the action button, this function will be activated, and the counter will keep on increasing from -1 to n.
  • This increment in the counter will take place every 1000 milliseconds.
  • In the end, this function will return the current counter time
  • StartTimer()
def StartTimer(lbl):
    global running
    running=True
    counter_label(lbl)
    start_btn['state']='disabled'
    stop_btn['state']='normal'
    reset_btn['state']='normal'
  • This is the function that will be called when user will user clicks on the start button.
  • counter_label function is called inside this function.
  • Every time the start button is clicked, it will be disabled immediately & the user won’t be able to click it again.
  • Also, it enables stop and reset buttons. That means users can click on these buttons.

StopTimer()

def StopTimer():
    global running
    start_btn['state']='normal'
    stop_btn['state']='disabled'
    reset_btn['state']='normal'
    running = False
  • These functions will be called when the user clicks on the stop button.
  • This will set the running to false.
  • That means the activity happening in the counter_label() function will stop now.
  • Also, it will disable the stop button & the user won’t be able to click it again.
  • and will enable the start & reset buttons.
  • So now the user can either resume the counter by clicking on the start button or reset it.

ResetTimer()

def ResetTimer(lbl):
    global counter
    counter=-1
    if running==False:      
        reset_btn['state']='disabled'
        lbl['text']='00'
    else:                          
        lbl['text']=''
  • The reset function is called when the user clicks on the Reset button.
  • The counter will again be set to the default value, i.e, -1
  • Running will be set to false, and text appearing on the main application window will be set to 00.
  • So in this way, everything will start appearing similar to the screen that appeared when the program was run.

Code:

from tkinter import *

ws = Tk()
ws.geometry('400x450+1000+300')
ws.title('PythonGuides: Stopwatch')
ws.config(bg='#299617')
ws.iconbitmap('stopwatch.ico')
ws.resizable(0,0)

counter = -1
running = False
def counter_label(lbl):
    def count():
        if running:
            global counter
            if counter==-1:             
                display="00"
            else:
                display=str(counter)

            lbl['text']=display    
            
            lbl.after(1000, count)    
            counter += 1
    count()     

def StartTimer(lbl):
    global running
    running=True
    counter_label(lbl)
    start_btn['state']='disabled'
    stop_btn['state']='normal'
    reset_btn['state']='normal'

def StopTimer():
    global running
    start_btn['state']='normal'
    stop_btn['state']='disabled'
    reset_btn['state']='normal'
    running = False

def ResetTimer(lbl):
    global counter
    counter=-1
    if running==False:      
        reset_btn['state']='disabled'
        lbl['text']='00'
    else:                          
        lbl['text']=''

bg = PhotoImage(file='stopwatch.png')
img = Label(ws, image=bg, bg='#299617')
img.place(x=75, y=50)

lbl = Label(
    ws, 
    text="00", 
    fg="black", 
    bg='#299617', 
    font="Verdana 40 bold"
    )

label_msg = Label(
    ws, text="minutes", 
    fg="black", 
    bg='#299617', 
    font="Verdana 10 bold"
    )

lbl.place(x=160, y=170)
label_msg.place(x=170, y=250)

start_btn=Button(
    ws, 
    text='Start', 
    width=15, 
    command=lambda:StartTimer(lbl)
    )

stop_btn = Button(
    ws, 
    text='Stop', 
    width=15, 
    state='disabled', 
    command=StopTimer
    )

reset_btn = Button(
    ws, 
    text='Reset', 
    width=15, 
    state='disabled', 
    command=lambda:ResetTimer(lbl)
    )

start_btn.place(x=30, y=390)
stop_btn.place(x=150, y=390)
reset_btn.place(x=270, y=390)

ws.mainloop()

Output:

python tkinter stopwatch

In this article, I have explained to you how to stopwatch using Python tkinter. I discussed an overview of a stopwatch in Python and a stopwatch source code with an explanation of all the terms I have used. Hope you understood the code and its explanation.

You may like the following Python tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.