I'm trying to continuously refresh a CTkinter frame, but the code keeps getting stuck in the TS_Button_Update()
function and the main window doesn't ever open (print(countdown)
repeatedly prints, however). I also eventually want the code to also update other characteristics of the GUI such as button colors based on variables - is there any way I can change the code such that it refreshes automatically in real time?
Here is a snippet of the code (the complete program is too long to paste here):
class HomeScreen(customtkinter.CTkFrame):
def TS_Button_Update(self,TS_progress_Button,temperature):
countdown = ser_ard1.readline().decode('ascii')
countdown = countdown.replace('\n','')
print(countdown)
temperature.set(countdown)
TS_progress_Button.configure(text = countdown)
TS_progress_Button.after(2000,self.TS_Button_Update(TS_progress_Button,temperature))
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
global TS_progress_Button, temperature
width, height = self.winfo_screenwidth(), self.winfo_screenheight()
rrw = width/1920
rrh= height/1080
countdown = ser_ard1.readline().decode('ascii')
countdown = countdown.replace('\n','')
temperature = StringVar()
temperature.set(countdown)
print(countdown)
TS_progress_Button=customtkinter.CTkLabel(self, fg_color=main_fg, bg_color=main_fg, text_color = 'white', width=rrw*225, height=rrh*20
, textvariable=temperature)
TS_progress_Button.place(x=rrw*750,y=rrh*1000)
self.TS_Button_Update(TS_progress_Button,temperature)
I've also tried other variations such as self.update()
after calling the TS_Button_Update()
for the first time (and removed the built in loop), as well as having the function place a new label at every iteration, and no luck. Can anyone help me figure out what I'm doing wrong please?
When calling TS_progress_Button.after(2000,self.TS_Button_Update(TS_progress_Button,temperature))
, you are not actualy passing a refenrence to TS_Button_Update
to be executed later, but calling it in place, what will cause the function to be stuck in a loop.
Replace this line with TS_progress_Button.after(2000, self.TS_Button_Update, TS_progress_Button, temperature)
.
This will schedule the function to be called after a delay of 2000 milliseconds, passing TS_progress_Button
and temperature
as arguments.
Regarding other gui components
The same approche can be used:
def update_button_color():
if some_condition:
TS_progress_Button.configure(bg='red')
else:
TS_progress_Button.configure(bg='green')
TS_progress_Button.after(1000, update_button_color) # The function will be called every second, since it calls itself
# Call the function once to start the periodic updates
update_button_color()