Search code examples
pythonuser-interfacetkintertkinter-scale

How to automatically update `tk.Label` when the value of `tk.Scale` changes?


I put in my frame scale, but I'm not sure how I can show the value of this scale in my label. I need to update it every time the scale moves. How can I do that?

self.options_settings.framepripojeni6 = Frame(self.options_settings.tab1)
        self.options_settings.framepripojeni6.pack(side=tkinter.TOP, expand=0, fill=tkinter.BOTH, padx=2, pady=4)

        self.options_settings.scale = Scale(self.options_settings.framepripojeni6,from_=1, to=60, length=350)
        self.options_settings.scale.pack(side=tkinter.TOP)

        self.options_settings.labelScale = tkinter.Label(self.options_settings.framepripojeni5, text="x")
        self.options_settings.labelScale.pack(side=tkinter.LEFT)

Solution

  • If the scale and label share a common variable, the label will automatically update. You can call the set method of the variable to provide a default value of the scale.

    Here's a simple example:

    import tkinter as tk
    
    root = tk.Tk()
    
    scalevar = tk.IntVar()
    scalevar.set(50)
    
    scale = tk.Scale(root, from_=0, to=100, 
                     variable=scalevar, orient="horizontal")
    label = tk.Label(root, textvariable=scalevar)
    
    scale.pack(side="top", fill="x", expand=True)
    label.pack(side="top", fill="x", expand=True)
    
    root.mainloop()