Search code examples
pythontkinterslidercustomtkinter

Customtkinter: Self updating label with text equal to value of slider. The label is not updating


I am trying to create a slider with a label below it showing the value of the slider. The label should be updating constantly on its own. I am facing some difficulty doing this. The label is not updating. (Note: This is in custom tkinter so some of the parameters may be different)

I tried this: -

from customtkinter import *


class App(CTk):
    def __init__(self):
        super().__init__()
        self.my_slider = CTkSlider(self, from_=0, to=500)
        self.my_slider.grid(row=0, column=0)

        self.slider_val = CTkLabel(self)
        self.slider_val.grid(row=1, column=0)
        
        self.update_()

    def update_(self):
        self.slider_val['text'] = self.my_slider.get()

        self.after(10, self.update_)
        
        
if __name__ == '__main__':
    app = App()
    app.mainloop()

The code worked fine (no exceptions were caused), yet, it seemed as though the update_() function did not get called.

Could someone please explain what caused this and help correct the problem?


Solution

  • If you associate the same IntVar with the label and slider, the label will automatically be updated.

    from customtkinter import *
    import tkinter as tk
    
    
    class App(CTk):
        def __init__(self):
            super().__init__()
    
            var = tk.IntVar()
            self.my_slider = CTkSlider(self, from_=0, to=500, variable=var)
            #                                               ^^^^^^^^^^^^^^
            self.my_slider.grid(row=0, column=0)
    
            self.slider_val = CTkLabel(self, textvariable=var)
            #                              ^^^^^^^^^^^^^^^^^^
            self.slider_val.grid(row=1, column=0)
    
    
    if __name__ == '__main__':
        app = App()
        app.mainloop()