我也試過這個起初heinzderaugust建議的方式:
button[i] = ttk.Button(loadProject, text=data_files[i], command = lambda i=data_files[i]:load(i)).grid(column=1, row=i, sticky=W)
我也可以用類作爲回調的中間部分,以解決這個問題: (這個課程是插件裏面viewProject)erted
class Command:
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
def __call__(self):
return(self.callback(*self.args, **self.kwargs))
然後我您的按鈕定義改爲:
button[i] = ttk.Button(loadProject, text=data_files[i], command = Command(load,data_files[i])).grid(column=1, row=i, sticky=W)
最後我改變了負載函數接受一個說法:
def load(myFile):
spamReader = csv.reader(open(myFile))
for row in spamReader:
a = list(row)
ttk.Label(loadProject, text=(a[0])).grid(column=4, row=0, sticky=W)
ttk.Label(loadProject, text=("\n"+a[1])).grid(column=4, row=1, sticky=W)
ttk.Label(loadProject, text=("\n"+a[2])).grid(column=4, row=2, sticky=W)
ttk.Label(loadProject, text=(a[3])).grid(column=4, row=3, sticky=W)
ttk.Label(loadProject, text=(a[4])).grid(column=4, row=4, sticky=W)
ttk.Label(loadProject, text=("\n"+a[5])).grid(column=4, row=5, sticky=W)
ttk.Label(loadProject, text=("\n"+a[6])).grid(column=4, row=6, sticky=W)
ttk.Label(loadProject, text=("\n\n"+a[7])).grid(column=4, row=7, sticky=W)
我不確定這會是最好的做法,但都行。
(當然,拉姆達的做法確實有點顯得更「Python化」)
來源:https://code.activestate.com/recipes/66521-avoiding-lambda-in-writing-callback-functions/
謝謝,我知道了現在的工作。我去了第二個,因爲它對我來說似乎更容易理解。 – Launch 2012-03-18 21:33:47