2017-04-24 76 views
0

我正在写一个简单的颜色选择器脚本使用Python和Tkinter的,我有这样的代码,它的工作原理:Python的Tkinter的规模lambda函数

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函数只有一个参数,但不起作用。我在网上查了一下,但由于我是初学者,所以无法将他们的解释应用到我的个案中。如果还有其他问题,请让我知道。顺便说一句,有一种使用像'发件人'这样的东西的方法吗?谢谢!

回答

0

The Scale provides 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() 
+0

谢谢你,我现在明白了!不知道命令可以传递一个论点。该参数将始终命名为'x'?如果我想用它作为第二个参数,我该怎么做?它看起来是默认情况下的第一个参数。 –

+0

Scale命令传递的参数未被命名;这是一个“立场论点”。它始终处于第一位,在我的代码中,我决定将其命名为“价值”。在您的原始代码中,它被命名为“x”。 Scale命令只传递一个参数,但如果它有多个参数,则会使您的def行匹配:'def(arg1,arg2)'。函数参数的数量和类型被称为“签名”。 – Novel