作者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/m.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