I'm trying to create several buttons with tkinter in a for loop, but I'm having some trouble with the command passed to them and, since the number of buttons I'll need to create isn't fixed, I can't create them manually (minesweeper game).
The buttons are correctly created and displayed in grid form, but the command is the same for all (that of the last button created).
My code looks something like:
rows = 5
columns = 5
buttons_dict = {}
for i, row in enumerate(range(rows)):
for j, column in enumerate(range(columns)):
buttons_dict[(i, j)] = tk.Button(top_board_frame, command=lambda: btn_click(i, j))
buttons_dict[(i, j)].grid(row=i, column=j)
My intention is to pass each button a function that, on click, returns the buttons' coordinates. Something like:
def btn_click(i, j):
current_pair = (i, j)
print(current_pair)
The problem with the code above is it return the coordinates of the last button created, no matter which button is clicked.