2017-04-24 72 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