Create a stopwatch using Tkinter in Python

Below is an example of how you can create a stopwatch using Tkinter in Python. This stopwatch will have start, stop, and reset functionalities.

import tkinter as tk
from tkinter import ttk
from time import strftime

class Stopwatch:
    def __init__(self, root):
        self.root = root
        self.root.title("Stopwatch")
        self.root.geometry("300x150")
        self.running = False
        self.counter = 0
        self.time_label = ttk.Label(root, text="00:00:00", font=("Helvetica", 48))
        self.time_label.pack(expand=True)

        self.start_button = ttk.Button(root, text="Start", command=self.start)
        self.start_button.pack(side="left", expand=True)

        self.stop_button = ttk.Button(root, text="Stop", command=self.stop)
        self.stop_button.pack(side="left", expand=True)

        self.reset_button = ttk.Button(root, text="Reset", command=self.reset)
        self.reset_button.pack(side="left", expand=True)

    def start(self):
        if not self.running:
            self.update()
            self.running = True

    def stop(self):
        if self.running:
            self.time_label.after_cancel(self.update_time)
            self.running = False

    def reset(self):
        self.stop()
        self.counter = 0
        self.time_label.config(text="00:00:00")

    def update(self):
        self.counter += 1
        time_str = strftime('%H:%M:%S', time.gmtime(self.counter))
        self.time_label.config(text=time_str)
        self.update_time = self.time_label.after(1000, self.update)

if __name__ == "__main__":
    root = tk.Tk()
    stopwatch = Stopwatch(root)
    root.mainloop()
  1. Imports:
    • tkinter and ttk for GUI elements.
    • strftime from time to format time.
  2. Stopwatch Class:
    • The __init__ method initializes the GUI components.
    • The start, stop, and reset methods control the stopwatch.
    • The update method updates the timer every second.
  3. Main Section:
    • The root window is created.
    • An instance of the Stopwatch class is created with root.
    • The Tkinter main loop is started with root.mainloop().

You can run this script to see a simple stopwatch with start, stop, and reset functionalities.

 

4o

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top