When I do label.config(text='changed'), it does not happen and stops the thread from closing.
Due to it, the exit_window function is not working.
The root window is becoming unresponsive and nothing is happening.
I am using the latest python version.
I have tried many things but it is not working. Please tell me where I am going wrong.
Code:
import tkinter
import threading
import time
import datetime
def format_time(secs: int) -> str:
"""Function that takes the total seconds and convert it to
hours, minutes and seconds and then print them."""
hours = secs // 3600
mins = secs // 60
secs = secs % 60
return f"{hours:02}:{mins:02}:{secs:02}"
def save_time() -> None:
global SECS
# If the time is not zero meaning if the watch is not stopped.
if SECS:
current_d_t = datetime.datetime.now()
filename = "Stopwatch " + current_d_t.strftime("%d-%M-%Y")
with open(filename, "a") as f:
f.write("TIME: " + format_time(SECS) + "\n\n")
def inc_stopwatch(time_label: tkinter.Label) -> None:
# Get total seconds
global SECS, IS_RUNNING
IS_RUNNING = True
while True:
print(IS_RUNNING)
SECS += 1
time.sleep(1)
time_label.config(text=format_time(SECS))
if not IS_RUNNING:
break
print("Ended while loop.")
def start_time(time_label: tkinter.Label):
global THREADS, IS_RUNNING
if not THREADS:
t = threading.Thread(target=inc_stopwatch, args=(time_label, ))
t.start()
THREADS.append(t)
else:
IS_RUNNING = True
def exit_window(root: object) -> None:
global IS_RUNNING, THREADS
IS_RUNNING = False
time.sleep(2)
print(IS_RUNNING)
if THREADS:
print(THREADS)
THREADS[0].join()
root.quit()
FONT = ('Areal', 20)
# Make the root window.
root = tkinter.Tk()
# Display the title.
root.title("Stopwatch")
# Set the screen size to 400 rows by 400 cols.
root.geometry('400x400')
# Total Seconds.
SECS = 0
# Boolean to start or stop the time.
IS_RUNNING = False
# Thread for increasing the time.
THREADS = []
# Label to display time.
time_label = tkinter.Label(root, text='00:00:00', font=FONT)
time_label.pack()
# Button to start stopwatch.
start_button = tkinter.Button(root, text='Start', font=FONT,
command=lambda: start_time(time_label))
start_button.pack()
# Button to pause stopwatch.
pause_button = tkinter.Button(root, text='Pause', font=FONT)
pause_button.pack()
# Button to reset time.
reset_button = tkinter.Button(root, text='Reset', font=FONT)
reset_button.pack()
# Button to exit window.
exit_button = tkinter.Button(root, text='Exit', font=FONT,
command=lambda: exit_window(root))
exit_button.pack()
root.mainloop()