Stopwatch Using Python and Tkinter

PythonPythonBeginner
Practice Now

Introduction

In this project, we will create a simple stopwatch application using Python and Tkinter. The stopwatch will have functionality to start, stop, reset, and quit. We will use the Tkinter library for the graphical user interface (GUI) components and the time library for time-related operations.

👀 Preview

Alt text

🎯 Tasks

In this project, you will learn:

  • How to import necessary libraries for GUI and time-related operations
  • How to define a StopWatch class that extends the Frame class
  • How to create GUI components for the stopwatch
  • How to update the elapsed time and display it in the GUI
  • How to implement functionality to start, stop, and reset the stopwatch
  • How to create a main function to initialize the StopWatch object and add buttons for interaction

🏆 Achievements

After completing this project, you will be able to:

  • Create a GUI application using Tkinter in Python
  • Work with time-related operations in Python
  • Implement functionality for a stopwatch

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) tkinter(("`Tkinter`")) -.-> tkinter/ThemedWidgetsGroup(["`Themed Widgets`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") tkinter/ThemedWidgetsGroup -.-> tkinter/label("`Text Label`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/keyword_arguments -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} tkinter/label -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/variables_data_types -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/numeric_types -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/type_conversion -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/conditional_statements -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/tuples -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/function_definition -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/default_arguments -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/importing_modules -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/using_packages -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/standard_libraries -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/classes_objects -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/constructor -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/polymorphism -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/encapsulation -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/data_collections -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} python/build_in_functions -.-> lab-298904{{"`Stopwatch Using Python and Tkinter`"}} end

Create the project files

First, create a new file named stopwatch.py and open it in your preferred code editor.

cd ~/project
touch stopwatch.py

Import necessary libraries

In the stopwatch.py file, start by importing the required libraries. We need Tkinter for GUI components, ttk for themed widgets, and time for time-related operations. Add the following code at the beginning of the file:

from tkinter import *
from tkinter import ttk
import time

Define the StopWatch class

Next, define a class named StopWatch that extends the Frame class. We will use this class to create the stopwatch functionality. Add the following code after the import statements:

class StopWatch(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        self._start = 0.0
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()

        self.makeWidgets()

Create the GUI components

Inside the StopWatch class, add a method named makeWidgets that creates and positions the GUI components. This method will be called from the constructor. Add the following code inside the StopWatch class:

    def makeWidgets(self):
        l = ttk.Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)

Update the elapsed time

Add a method named _update inside the StopWatch class. This method will calculate the elapsed time and update the GUI. Add the following code inside the StopWatch class:

    def _update(self):
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

Set the time

Add a method named _setTime inside the StopWatch class. This method will format the time and update the timestr variable. Add the following code inside the StopWatch class:

    def _setTime(self, elap):
        minutes = int(elap / 60)
        hours = int(minutes / 60)
        seconds = int(elap - minutes * 60.0)
        hseconds = int((elap - minutes * 60.0 - seconds) * 100)
        self.timestr.set('%02d:%02d:%02d:%02d' % (hours, minutes, seconds, hseconds))

Implement the start functionality

Add a method named Start inside the StopWatch class. This method will start the stopwatch. Add the following code inside the StopWatch class:

    def Start(self):
        if not self._running:
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1

Implement the stop functionality

Add a method named Stop inside the StopWatch class. This method will stop the stopwatch. Add the following code inside the StopWatch class:

    def Stop(self):
        if self._running:
            self.after_cancel(self._timer)
            self._elapsedtime = time.time() - self._start
            self._setTime(self._elapsedtime)
            self._running = 0

Implement the reset functionality

Add a method named Reset inside the StopWatch class. This method will reset the stopwatch. Add the following code inside the StopWatch class:

    def Reset(self):
        self._start = time.time()
        self._elapsedtime = 0.0
        self._setTime(self._elapsedtime)

Create the main function

Add a main function outside the StopWatch class. This function will create the main application window, initialize the StopWatch object, and add buttons for start, stop, reset, and quit. Add the following code after the StopWatch class:

def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)

    Button(root, text='Start', command=sw.Start).pack(side=LEFT)
    Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)

    root.mainloop()


if __name__ == '__main__':
    main()

Run the project

Finally, swicth to Desktop and run the project using the following command:

python stopwatch.py
Alt text

Summary

Congratulations! You have successfully created a stopwatch application using Python and Tkinter. We went through the steps of creating the project files, importing necessary libraries, defining the StopWatch class, creating GUI components, updating the elapsed time, implementing start, stop, and reset functionality, and creating the main application. You can now run the project and use the buttons to control the stopwatch.

Other Python Tutorials you may like