How to move the slider of scale slider with the value of two scale slider with tkinter in Python?

I want to make three scale slider in tkinter in Python, where I can move the slider of first two and the third slider moves itself as the sum of the values of first two sliders

I tried with the following code where I try to set the value of first two to the third.

from tkinter import *
master = Tk()
#First Scale
w1=Scale(master, from_=0, to=100,orient=HORIZONTAL) 
w1.pack() 
#Second Scale
w2=Scale(master, from_=0, to=200,orient=HORIZONTAL) 
w2.pack() 

#Third Scale where sum has to be shown
w3=Scale(master, from_=0, to=300,orient=HORIZONTAL) 
w3.set(w1.get()+w2.get())
w3.pack() 
mainloop()

The expectation is to move the first two sliders and the third slider moves itself to the value which is sum of the values of first two sliders.

Upvotes: 0

Views: 1159

Answers (1)

Henry Yik
Henry Yik

Reputation: 22503

You can create two IntVar as variables for your first two Scale, then trace the changes and set the third Scale.

from tkinter import *
master = Tk()
#First Scale
w1_var = IntVar()
w1=Scale(master, from_=0, to=100, variable=w1_var, orient=HORIZONTAL)
w1.pack()
#Second Scale
w2_var = IntVar()
w2=Scale(master, from_=0, to=200, variable=w2_var, orient=HORIZONTAL)
w2.pack()   

#Third Scale where sum has to be shown
w3=Scale(master, from_=0, to=300,orient=HORIZONTAL,state="disabled")
w3.pack()

def trace_method(*args):
    w3.config(state="normal")
    w3.set(w1.get() + w2.get())
    w3.config(state="disabled")

w1_var.trace("w", trace_method)
w2_var.trace("w", trace_method)

master.mainloop()

Upvotes: 1

Related Questions