Re: [问题] 请问有人可以帮我看一下Tkinter吗???谢谢!!

楼主: Pomay (右脚)   2014-05-05 18:06:03
来献丑一下,虽然可能不算太正规的做法
以下是按Button会修改同一row的label背景颜色
修改了button的command用的function
from Tkinter import *
the_window = Tk()
the_window.title('ONE Button Colour')
start_color = 'grey'
button_color = ['Red', 'Green', 'Blue', 'Yellow', 'Orange']
for r in range(5):
colour = Label(the_window, bg = start_color, compound = 'bottom',
width = 8,height = 1)
colour.grid(row=r,column=0, padx = 2, pady = 3)
Button(the_window, text = button_color[r],
command = lambda lbl=colour,r=r:lbl.config(bg=button_color[r].lower()),
width = 8,height = 1 ).grid(row=r,column=1, padx = 2, pady = 7)
the_window.mainloop()
以下观念如果有错,请不吝指正,谢谢。
使用lambda来当button的呼叫函数,
在lambda的参数位置先给予默认值:当时的Label与r。
在button按下时呼叫了lambda的函数,
因为button command呼叫时没有带参数,
lambda的参数就会取用默认值,
所以会传入当时的Label与r,
就可以修改label的bg值了。
个人还满爱用这种技巧,
不过不知道算不算旁门左道就是了.....
作者: LiloHuang (十年一刻)   2014-05-05 18:25:00
我比较推荐 from functools import partialcommand = partial(lambda lbl,r:lbl.config(bg=button_color[r].lower()), colour, r), 来达成 callable wrapper 的效果 :P
楼主: Pomay (右脚)   2014-05-05 19:17:00
推楼上,又学到一招
作者: aeronan (aeron)   2014-05-07 15:26:00
原来如此~~受教了~~谢谢大大们!!!

Links booklink

Contact Us: admin [ a t ] ucptt.com