【问题标题】:TKinter using an indexing for loop to pass arguments for a button command [duplicate]TKinter 使用索引 for 循环来传递按钮命令的参数 [重复]
【发布时间】:2016-12-03 22:42:18
【问题描述】:

我有以下一段代码,我在其中创建了一系列按钮,以在创建的数字类上运行增加或减少方法。

    for idx in range(len(self._priceNums)):
        Button(window, text='^', command=lambda: self.incNum(idx)).grid(row=0, column=numInColumn)
        Label(window, textvariable=self._priceNums[idx]).grid(row=1, column=numInColumn)
        Button(window, text='v', command=lambda: self.decNum(idx)).grid(row=2, column=numInColumn)
        numInColumn += 1

该功能在列表中的选定对象上按预期工作,但我的问题是让按钮对正确的对象进行操作。

lamba: self.incNum(idx)

似乎只有在按下按钮时才读取 idx。因此,每个按钮仅在列表中的最后一个对象上运行该方法。有没有办法以这种方式创建一系列按钮,每个按钮对应于该列表中各自的数字对象。下面是方法供参考

def incNum(self, idx):
    self._priceNums[idx].set(self.game._adjustedPrice[idx].incNum())

请注意,这可能有用也可能没有帮助:

_priceNums 是 StringVars 的列表,对应于 _adjustedPrice 中数字对象的值

谢谢!

【问题讨论】:

    标签: python for-loop button indexing tkinter


    【解决方案1】:

    您需要将 idx 变量传递给 lambda 函数。

    for idx in range(len(self._priceNums)):
        Button(window, text='^', command=lambda idx=idx: self.incNum(idx)).grid(row=0, column=numInColumn)
        Label(window, textvariable=self._priceNums[lambda idx=idx: idx]).grid(row=1, column=numInColumn)
        Button(window, text='v', command=lambda idx=idx: self.decNum(idx)).grid(row=2, column=numInColumn)
        numInColumn += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多