└── Create a simple stopwatch /Create a simple stopwatch: -------------------------------------------------------------------------------- 1 | import tkinter as Tkinter 2 | from datetime import datetime 3 | counter = 0 4 | running = False 5 | 6 | 7 | def counter_label(label): 8 | def count(): 9 | if running: 10 | global counter 11 | # To manage the intial delay. 12 | if counter == 0: 13 | display = 'Ready!' 14 | else: 15 | tt = datetime.utcfromtimestamp(counter) 16 | string = tt.strftime('%H:%M:%S') 17 | display = string 18 | 19 | label['text'] = display 20 | 21 | # label.after(arg1, arg2) delays by 22 | # first argument given in milliseconds 23 | # and then calls the function given as second argument. 24 | # Generally like here we need to call the 25 | # function in which it is present repeatedly. 26 | # Delays by 1000ms=1 seconds and call count again. 27 | label.after(1000, count) 28 | counter += 1 29 | 30 | # Triggering the start of the counter. 31 | count() 32 | 33 | 34 | # start function of the stopwatch 35 | def Start(label): 36 | global running 37 | running = True 38 | counter_label(label) 39 | start['state'] = 'disabled' 40 | stop['state'] = 'normal' 41 | reset['state'] = 'normal' 42 | 43 | 44 | # Stop function of the stopwatch 45 | def Stop(): 46 | global running 47 | start['state'] = 'normal' 48 | stop['state'] = 'disabled' 49 | reset['state'] = 'normal' 50 | running = False 51 | 52 | 53 | # Reset function of the stopwatch 54 | def Reset(label): 55 | global counter 56 | counter = 0 57 | # If reset is pressed after pressing stop. 58 | if not running: 59 | reset['state'] = 'disabled' 60 | label['text'] = '00:00:00' 61 | # If reset is pressed while the stopwatch is running. 62 | else: 63 | label['text'] = '00:00:00' 64 | 65 | 66 | root = Tkinter.Tk() 67 | root.title("Stopwatch") 68 | 69 | # Fixing the window size. 70 | root.minsize(width=250, height=70) 71 | label = Tkinter.Label(root, text='Ready!', fg='black', font='Verdana 30 bold') 72 | label.pack() 73 | f = Tkinter.Frame(root) 74 | start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label)) 75 | stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop) 76 | reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label)) 77 | f.pack(anchor='center', pady=5) 78 | start.pack(side='left') 79 | stop.pack(side='left') 80 | reset.pack(side='left') 81 | root.mainloop() 82 | --------------------------------------------------------------------------------