Python Tkinter Stopwatch (stopwatch source code in Python)

In this tutorial, we will learn how to create a simple stopwatch using Python tkinter. It is easy to create a stopwatch in Python. Let us start with the Python Tkinter stopwatch.

About 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 the infinite seconds if reset or stop is not pressed.
  • Backward Stopwatch is provided with the 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 Start, Stop & 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.

Stopwatch source code in Python

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

Step 1:

Import everything from tkinter module

from tkinter import *

Step 2:

Configure 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 of 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. default icon is feature.
  • resizable determines the amount window that can be stretched by user.
    • it accepts x and y value
    • in this case value is 0, 0 that means window can’t be resized.
READ:  Compare two integers in Python Django

Step 3: Place an image of 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 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 under 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 we cannot pass the 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 a global variable.
  • 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 counter will also have counter value as 10.
READ:  How to Remove Empty Keys From Dictionary Python

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 if statement will work till the time running is true.
  • 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 user will click on the action button this function will be activated and the counter will keep on increasing from -1 to n.
  • This increment in counter will take place every 1000 mili-seconds.
  • 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 will click on the stop button.
  • this will set the running to false.
  • That means, activity happening in the counter_label() function will stop now.
  • also, it will disable the stop button & the user won’t beable to click it again.
  • and will enable the start & reset buttons.
  • So now user either can resume the counter by clicking on the start button or can reset it.
READ:  Python Tkinter TreeView – How to Use

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 et to default value i.e -1
  • Running will 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

You may like the following Python tutorials:

I hope now you can create a stopwatch in python and learn how to use the python stopwatch class and python stopwatch module. Here we learned about the Python Tkinter stopwatch and you got the stopwatch source code in Python.