我正在使用字典来存储我的按钮,正如您在main方法中看到的那样。 “ self.tables”是带有表名的列表。因此,for循环中的“ i”是表的名称,该表在文本上显示为按钮。每个按钮应具有不同的命令,如您在下面看到的self.edit(i)。但是,当您按下特定按钮而不是运行self.edit(i)时,始终运行的是i的最新迭代,而不是创建特定按钮时使用的i。
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
self.title = Label(self, text="", font=("arial", 20))
self.title.grid(row=0, column=0)
self.table = ""
self.widgetdata = {}
def main(self):
for x in self.widgetdata:
self.widgetdata[x].grid_forget()
self.tables = GuiSetup.tbls
self.title["text"] = "Select table to edit:"
for j,i in enumerate(self.tables):
self.widgetdata[i] = Button(self, text=i, command=lambda: self.edit(i)) # When any of these buttons are pressed the most recent button command is run
self.widgetdata[i].grid(row=j+1, column=0)
self.controller.show_frame("Edit Menu")
# Sets up the Editmenu gui for editing the specified table
def edit(self, table, id="new"):
print(table)
self.table = table
self.id = id
上面的代码是类及其方法的一部分。我不知道为什么会这样,因为所有按钮上的文本都是唯一的,但是每个按钮的命令都不是所设置的。任何建议,将不胜感激。谢谢
替换
self.widgetdata[i] = Button(self, text=i, command=lambda: self.edit(i))
作者
self.widgetdata[i] = Button(self, text=i, command=lambda i=i: self.edit(i))
说明: lambda函数的主体在单击按钮时执行,因此它在执行时(即最后创建的Button的索引)而不是在定义时使用i
的当前值。创建别名自变量会强制为每个循环步骤创建一个局部变量,每个局部变量具有不同的值,因此请引用不同的Button。