Re: [問題] 請問有人可以幫我看一下Tkinter嗎???謝謝!!

看板Python作者 (右腳)時間11年前 (2014/05/05 18:06), 編輯推噓2(204)
留言6則, 3人參與, 最新討論串2/2 (看更多)
來獻醜一下,雖然可能不算太正規的做法 以下是按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值了。 個人還滿愛用這種技巧, 不過不知道算不算旁門左道就是了..... -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.169.173.130 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1399284366.A.BEC.html

05/05 18:25, , 1F
我比較推薦 from functools import partial
05/05 18:25, 1F

05/05 18:26, , 2F
command = partial(lambda lbl,r:lbl.config(
05/05 18:26, 2F

05/05 18:26, , 3F
bg=button_color[r].lower()
05/05 18:26, 3F

05/05 18:27, , 4F
), colour, r), 來達成 callable wrapper 的效果 :P
05/05 18:27, 4F

05/05 19:17, , 5F
推樓上,又學到一招
05/05 19:17, 5F

05/07 15:26, , 6F
原來如此~~受教了~~謝謝大大們!!!
05/07 15:26, 6F
文章代碼(AID): #1JPsAEli (Python)
文章代碼(AID): #1JPsAEli (Python)