I am creating a countdown timer GUI using Tkinter where the user selects the number of seconds that the countdown is for, using the built in scale feature. The countdown itself seemed to be working but even when the slider is moved up, it will countdown from the lowest ('from_') value of 40. I tried to change the .get() value to a local variable and put this into the function, the countdown no longer works and simply displays the number that the slider was set to (though it is now changing based on user input). I will paste the code below which hopefully clears up any ambiguity. Also, attempting it without the global variable and with the variable only outside the function creates an error (referenced before assignment). Any help appreciated. The code below is the local variable version:
window = tk.Tk()
window.configure(bg='black')
window.title('TUT Timer')
slider = tk.Scale(window, from_=40, to=60, fg='#39FF14', bg='black', orient=HORIZONTAL)
slider.grid(sticky='nsew')
time_var = slider.get()
def timer():
time_var = slider.get()
if time_var > 0:
time_label.config(text=time_var)
time_var = time_var -1
time_label.after(1000, timer)
elif time_var == 0:
time_label.config(text='0')
def start_button():
timer()
start = tk.Button(text='Start', command=start_button, bg='black', fg='#39FF14')
start.grid()
time_label = tk.Label(text = '00:00', height = 3, bg= 'black', fg= '#39FF14')
time_label.config(font=('Courier New', 20))
time_label.grid(sticky='nsew')
window.mainloop()
Where I used a global variable, the code was the same but with global time_var above or in place of time_var = slider.get() within the timer function (tried both, in place of creates a working countdown but not starting at the scale value).
To summarise there were two versions of the code that ran, but neither fully worked. One used a global variable but the scale feature .get didn't change based on the slider changing. The other option used the same variable but as a local variable, where the result was that the start number was simply displayed rather than the countdown starting. Appreciate any help in getting this working if possible!