Advertisement
CodeCrusader

Stopwatch App GUI

Jun 10th, 2023
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | Software | 0 0
  1. import tkinter as tk
  2. import time
  3.  
  4. # Initialize the window
  5. window = tk.Tk()
  6. window.title("Stopwatch")
  7.  
  8. # Stopwatch variables
  9. start_time = 0
  10. elapsed_time = 0
  11. is_running = False
  12.  
  13. # Label to display the stopwatch time
  14. time_label = tk.Label(window, text="00:00:00", font=("Helvetica", 48))
  15. time_label.pack(pady=10)
  16.  
  17. # Function to start the stopwatch
  18. def start_stopwatch():
  19.     global start_time, is_running
  20.  
  21.     if not is_running:
  22.         is_running = True
  23.         start_time = time.time()
  24.         update_stopwatch()
  25.  
  26. # Function to stop the stopwatch
  27. def stop_stopwatch():
  28.     global is_running
  29.  
  30.     if is_running:
  31.         is_running = False
  32.  
  33. # Function to reset the stopwatch
  34. def reset_stopwatch():
  35.     global elapsed_time, is_running
  36.  
  37.     elapsed_time = 0
  38.     is_running = False
  39.     time_label.config(text="00:00:00")
  40.  
  41. # Function to update the stopwatch time
  42. def update_stopwatch():
  43.     global elapsed_time
  44.  
  45.     if is_running:
  46.         elapsed_time = time.time() - start_time
  47.  
  48.     minutes = int(elapsed_time // 60)
  49.     seconds = int(elapsed_time % 60)
  50.     milliseconds = int((elapsed_time % 1) * 100)
  51.  
  52.     time_string = f"{minutes:02d}:{seconds:02d}:{milliseconds:02d}"
  53.     time_label.config(text=time_string)
  54.  
  55.     window.after(10, update_stopwatch)
  56.  
  57. # Create buttons for stopwatch control
  58. start_button = tk.Button(window, text="Start", command=start_stopwatch)
  59. start_button.pack(side=tk.LEFT, padx=5)
  60.  
  61. stop_button = tk.Button(window, text="Stop", command=stop_stopwatch)
  62. stop_button.pack(side=tk.LEFT, padx=5)
  63.  
  64. reset_button = tk.Button(window, text="Reset", command=reset_stopwatch)
  65. reset_button.pack(side=tk.LEFT, padx=5)
  66.  
  67. window.mainloop()
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement