作者timTan (用口头禅区分年记)
看板Python
标题Re: [问题] tkinter command 传参数问题
时间Fri Jan 20 01:45:20 2012
※ 引述《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)
1F:推 kfrico:太感谢你了 01/20 09:40