Python Tkinter Scale lambda函数

时间:2017-04-24 18:26:28

标签: python lambda tkinter

我正在用python和tkinter编写一个简单的颜色选择器脚本,我有这个代码并且它可以工作:

from tkinter import *

color = [0,0,0]

def convert_color(color):
 return '#{:02x}{:02x}{:02x}'.format(color[0],color[1],color[2])

def show_color(x,i):
 color[int(i)] = int(x)
 color_label.configure(bg=convert_color(color))

root = Tk()
color_label = Label(bg=convert_color(color),width=20)

rgb = [0,0,0]
for i in range(3):
 rgb[i] = Scale(orient='horizontal',from_=0,to=255,command=lambda x, y=i: 
 show_color(x,y))
 rgb[i].grid(row=i,column=0)

color_label.grid(row=3,column=0)

if __name__ == '__main__':
 mainloop()

我甚至不知道我是怎么做到的,但它运作正常。我不明白为什么我没有指定x,但我仍然需要它,当我滑动刻度时它的值会更新? show_color函数有一个参数但它不起作用。我在网上查了一下,但由于我是初学者,我不能将他们的解释应用到我的特定情况。如果有任何其他问题,请告诉我。 BTW有没有办法使用“发送者”这样的东西?谢谢!

1 个答案:

答案 0 :(得分:0)

比例尺提供x。当您向Scale小部件提供函数时,它会使用当前值调用该函数。

我会以理智的方式重写您的代码,以便您可以更好地遵循它:

from tkinter import *

color = [0,0,0] # standard red, green, blue (RGB) color triplet

def convert_color(color):
    '''converts a list of 3 rgb colors to an html color code
    eg convert_color(255, 0, 0) -> "#FF0000
    '''
    return '#{:02X}{:02X}{:02X}'.format(color[0],color[1],color[2])

def show_color(value, index):
    '''
    update one of the color triplet values
    index refers to the color. Index 0 is red, 1 is green, and 2 is blue
    value is the new value'''
    color[int(index)] = int(value) # update the global color triplet
    hex_code = convert_color(color) # convert it to hex code
    color_label.configure(bg=hex_code) #update the color of the label
    color_text.configure(text='RGB: {!r}\nHex code: {}'.format(color, hex_code)) # update the text

def update_red(value):
    show_color(value, 0)
def update_green(value):
    show_color(value, 1)
def update_blue(value):
    show_color(value, 2)

root = Tk()

red_slider = Scale(orient='horizontal',from_=0,to=255,command=update_red)
red_slider.grid(row=0,column=0)

green_slider = Scale(orient='horizontal',from_=0,to=255,command=update_green)
green_slider.grid(row=1,column=0)

blue_slider = Scale(orient='horizontal',from_=0,to=255,command=update_blue)
blue_slider.grid(row=2,column=0)

color_text = Label(justify=LEFT)
color_text.grid(row=3,column=0, sticky=W)

color_label = Label(bg=convert_color(color),width=20)
color_label.grid(row=4,column=0)

mainloop()