Jack
Jack

Reputation: 1437

Tkinter - pass multiple scale value to a label

I want to display the selected scale value on the label. Currently I have to create separate labels to print the values. Is there a clever way to pass all scale values I select to the same label to print?

l1 = tk.Label(window, bg='yellow', width=50, text='empty')
l1.pack()

l2 = tk.Label(window, bg='yellow', width=50, text='empty')
l2.pack()

def print_selection1(v):
    l1.config(text='You have selected ' + v +' trucks')

def print_selection2(v):
    l2.config(text='Truck Capacity is: ' + v + ' kg')


s1 = tk.Scale(window, label='Number of 7.5t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1, command=print_selection1)
s1.pack()

s2 = tk.Scale(window, label='Number of 12t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1, command=print_selection2)
s2.pack()

Upvotes: 0

Views: 872

Answers (2)

j_4321
j_4321

Reputation: 16169

You can keep the current scales values in a values list and use string formatting:

import tkinter as tk
window = tk.Tk()

l = tk.Label(window, bg='yellow', width=50, text='empty\nempty')
l.pack()

values = [0, 0]

def print_selection(scale, v):
    # update scale value
    values[scale] = v  
    # update display
    l.config(text='You have selected {} trucks\nTruck Capacity is: {} kg'.format(*values))

s1 = tk.Scale(window, label='Number of 7.5t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1,
             command=lambda v: print_selection(0, v))
s1.pack()

s2 = tk.Scale(window, label='Number of 12t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1,
             command=lambda v: print_selection(1, v))
s2.pack()

window.mainloop()

Upvotes: 1

Nouman
Nouman

Reputation: 7313

Yes it is possible. In addition to keeping the values in a single Label you can also make a single function for editing the values. Unlike other answer, you can use <Scale>.get() to get the current value of the scale. Here is the code:

import tkinter as tk
window = tk.Tk()

l1 = tk.Label(window, bg='yellow', width=50, text='empty'+'\n'+'empty')

l1.pack()

def edited(event):
    l1.config(text='You have selected ' + str(s1.get()) +' trucks'+"\n"+"Truck Capacity is: "+  str(s2.get()) + " kg")
    #               ---------------------text1------------------+newline+---------------------text2--------------------

s1 = tk.Scale(window, label='Number of 7.5t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1, command=edited)
s1.pack()

s2 = tk.Scale(window, label='Number of 12t truck', from_=0, to=30, orient=tk.HORIZONTAL,
             length=400, showvalue=0, tickinterval=5, resolution=1, command=edited)
s2.pack()

tk.mainloop()

Upvotes: 1

Related Questions