【问题标题】:Creating Tkinter buttons in a loop and setting the command for each button to take in the indices of the loop [duplicate]在循环中创建 Tkinter 按钮并为每个按钮设置命令以获取循环的索引 [重复]
【发布时间】:2021-09-19 11:31:50
【问题描述】:
 def run_game(self):

        root = Tk()

        for i in range(0, 6):
            for j in range(0, len(self.board[i])):
            
                button = Button(root, text="0", height=2, width=10, command=lambda: self.if_clicked_square(i,j))
                button.place(x=25 + (100 * j), y=100 + (100 * i))

                # button.pack()
                self.buttonsList[i].append([button])

        root.mainloop()

上述功能是使用 Tkinter 创建一个由 28 个按钮组成的 GUI 板。我使用嵌套的 for 循环来创建每个按钮并将其放置在板上以及按钮列表中。为每个按钮设置命令时会出现问题。我想为命令使用函数if_clicked_square(i,j)。该函数使用 i 和 j 索引进行操作。问题是循环完成后每个按钮的命令都是if_clicked_square(5,2),这恰好是循环的最后一个索引。我希望每个按钮都有一个基于 for 循环索引的唯一命令。例如,一个按钮应该有命令if_clicked_square(0,0),一个应该有命令if_clicked_square(1,0),等等所有28个按钮。我可以得到任何提示来完成此操作吗?

【问题讨论】:

    标签: python loops tkinter button


    【解决方案1】:

    使用循环时需要在lambda中创建局部变量

    button = Button(root, text="0", height=2, width=10, command=lambda x_p=i,y_p=j: self.if_clicked_square(x_p,y_p))
    button.place(x=25 + (100 * j), y=100 + (100 * i))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-28
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多