【问题标题】:tkinter button different command for loop in dictionary not working [duplicate]tkinter按钮字典中循环的不同命令不起作用[重复]
【发布时间】:2020-04-13 19:25:04
【问题描述】:

正如您在 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

上面的代码是一个类及其方法的一部分。 我不知道为什么会发生这种情况,因为所有按钮上的文本都是唯一的,但每个按钮的命令不是它设置的。任何建议,将不胜感激。谢谢

【问题讨论】:

    标签: python tkinter python-3.6 python-3.4


    【解决方案1】:

    替换

    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 的索引),而不是在定义时。创建别名参数会强制为每个循环步骤创建一个局部变量,每个变量都有不同的值,因此引用不同的 Button。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2018-01-24
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2012-05-13
      • 2018-12-19
      • 1970-01-01
      相关资源
      最近更新 更多