Ben Parker
Ben Parker

Reputation: 67

Changing TkInter Scale won't update label "bg"

Here is my code:

slowColor = (255,0,255)

window = Tk()
window.title = 'Mouse Tracker'

label1 = Label(window, text='Slow Color')
label1.grid(row=1, column=3, columnspan=5)
label2 = Label(window, bg='#%02x%02x%02x' % slowColor)
label2.grid(row=2, column=1, rowspan=2, columnspan=9, sticky=NW+SE)
label3 = Label(window, text='R')
label3.grid(row=4, column=2)
label4 = Label(window, text='G')
label4.grid(row=4, column=5)
label5 = Label(window, text='B')
label5.grid(row=4, column=8)
slider1 = Scale(window, from_=255, to=0)
slider1.grid(row=5, column=2, rowspan=6)
slider2 = Scale(window, from_=255, to=0)
slider2.grid(row=5, column=5, rowspan=6)
slider3 = Scale(window, from_=255, to=0)
slider3.grid(row=5, column=8, rowspan=6)
label2.config(bg='#%02x%02x%02x' % (slider1.get(), slider2.get(), slider3.get()))

What's supposed to happen is that changing the value of one of the sliders, should change the "bg" color of label2. But that isn't happening. Label2 remains static.

Upvotes: 0

Views: 208

Answers (1)

Nae
Nae

Reputation: 15345

"Changing TkInter Scale won't update label “bg”"

That is false. The Scale widgets you have have the value of 0, and you configure the label2's background to their values at the time that they are 0, thus the label is black, as '#000000' is black.

In order to dynamically update something whenever a Scale's value is changed, use command option in Scale:

def update():
    global label2, slider1, slider2, slider3
    label2.config(bg='#%02x%02x%02x' % (slider1.get(), slider2.get(), slider3.get()))

...

slider1['command'] = lambda scale_value: update()
slider2['command'] = lambda scale_value: update()
slider3['command'] = lambda scale_value: update()

Alternatively, command already passes Scale's value but it may yield extra overhead in this case.

Upvotes: 2

Related Questions