在循环中创建 Tkinter 按钮并为每个按钮设置命令以获取循环的索引
Creating Tkinter buttons in a loop and setting the command for each button to take in the indices of the loop
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)
,依此类推。我可以获得完成此操作的任何提示吗?
使用循环时需要在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))
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)
,依此类推。我可以获得完成此操作的任何提示吗?
使用循环时需要在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))