Tkinter-将多个刻度值传递给标签

时间:2018-08-14 13:41:35

标签: python user-interface tkinter

我想在标签上显示选定的比例值。目前,我必须创建单独的标签来打印值。是否有一种巧妙的方法将我选择的所有比例值传递到同一标签上进行打印?

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()

2 个答案:

答案 0 :(得分:1)

您可以将当前比例值保存在values列表中,并使用字符串格式:

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()

答案 1 :(得分:1)

是的,有可能。除了将值保存在单个Label中之外,您还可以使用单个函数来编辑值。与其他答案不同,您可以使用<Scale>.get()来获取刻度的当前值。这是代码:

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()