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

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
âœĻ Check Solution and Practice

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
âœĻ Check Solution and Practice

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()
âœĻ Check Solution and Practice

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)
âœĻ Check Solution and Practice

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)
âœĻ Check Solution and Practice

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))
âœĻ Check Solution and Practice

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
âœĻ Check Solution and Practice

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
âœĻ Check Solution and Practice

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)
âœĻ Check Solution and Practice

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()
âœĻ Check Solution and Practice

Run the project

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

python stopwatch.py
Alt text
âœĻ Check Solution and Practice

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