将函数绑定到在tkinter循环中创build的button

我写了一个for循环来根据Excel工作簿中的页数创buildbutton。 但是,我很难绑定function,打印每张纸上的数据。 谁能帮忙? 谢谢。 这是我所做的

wb = xlrd.open_workbook('file_path.xlsx') sheetnames = wb.sheet_names() num_sheets = len(sheetnames) def load_sheet(): for d in range(0, num_sheets): print(sheetnames[d]) for i in range(0, num_sheets): an_sheet = ttk.Button(self, text = "%s" % sheetnames[i], command= lambda : load_data) an_sheet.grid(row = 1, column = i+1, sticky='w', pady = 10, padx = 10) 

如果您在for循环中使用lambda,这是一个常见的初学者问题,因为初学者没有意识到lambda是迟绑定的。 换句话说,当命令参数被设置时,它总是使用“i”的最后一个值,而不是“i”的值。 在这种情况下,您需要使用functools.partial

 from functools import partial # ... for i in range(0, num_sheets): an_sheet = ttk.Button(self, text = "%s" % sheetnames[i], command=partial(function, i)) an_sheet.grid(row = 1, column = i+1, sticky='w', pady = 10, padx = 10)