Re: [問題] tkinter command 傳參數問題

看板Python作者 (用口頭禪區分年記)時間14年前 (2012/01/20 01:45), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《kfrico (霧峰小霸王)》之銘言: : for i in range(0,3): : g[i]=tk.Button(sf,text = '按鈕',command=lambda:myfunction(i)) : g[i].grid(row=row_num,column=3) : 為什麼在myfunction接收參數時都是2 : 是我寫錯那裡嗎? 這裡我覺得用closure 有點難懂。 你可以參考一下functools. import functools def myfun(i): return i commands = [] for i in range(3): commands.append(functools.partial(myfun,i)) for c in commands: print c() # 0, 1, 2 commands = [] for i in range(3): commands.append(lambda :myfun(i)) for c in commands: print c() # 2 2 2 這樣會比較happy 一些 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.87.142.18 ※ 編輯: timTan 來自: 219.87.142.18 (01/20 01:53)

01/20 09:40, , 1F
太感謝你了
01/20 09:40, 1F
文章代碼(AID): #1F65QoWK (Python)
討論串 (同標題文章)
文章代碼(AID): #1F65QoWK (Python)