作者IAMPF (PF)
看板Python
标题[问题] 传递参数问题
时间Sun Dec 20 12:25:09 2015
各位大大们好
最近在研究Tkinter写视窗程式,遇到一个问题
比如我今天创一个Button
def a():
print 'Hello'
b = Button(root, text='click', command=a)
问题就在这个command=a
通常a这个function不能带参数
有办法写一个a是可以传参数进去的吗
比如
def a(arg1, arg2):
print arg1, arg2
不知道要改的地方是在Button那边还是说在a那边
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 111.248.5.102
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1450585512.A.47D.html
1F:推 Thisisnotptt: 假如是lambda function能吗? 可以的话就可以带入变 12/20 12:37
2F:→ Thisisnotptt: 数了 12/20 12:37
from Tkinter import *
root = Tk()
def a(arg):
print arg
for i in range(10):
b = Button(root,text=str(i), command=lambda:a(i))
b.pack()
root.mainloop()
改了下程式码,是可以传进参数了,但是印出来每个值都是9是为什麽呢?
※ 编辑: IAMPF (111.248.5.102), 12/20/2015 12:55:44
3F:→ alibuda174: 改成 lambda i=i:a(i) 12/20 16:15
5F:→ IAMPF: 可以了耶!感谢! 12/20 16:22