在循环中创建 Tkinter 按钮并为每个按钮设置命令以获取循环的索引

时间:2021-07-09 04:00:11

标签: python loops tkinter button

 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 循环索引的唯一命令。例如,对于所有 28 个按钮,其中一个按钮应具有命令 if_clicked_square(0,0),一个按钮应具有命令 if_clicked_square(1,0),依此类推。我可以获得任何提示来完成此操作吗?

1 个答案:

答案 0 :(得分:0)

使用循环时需要在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)) 中创建局部变量

// KeyManagementClient is a client for interacting with Cloud Key Management Service (KMS) API.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.