Jun-21-2023, 02:20 PM
I'm looking to create buttons that remember where they are are in a 2D list. This way they can share a single function that takes their 2D list indices as parameters. Ultimately, I want the button to be able to manipulate its own text without having to have a separate reference for each button outside of the list and without having to have a separate function associated with each button.
The buttons display properly with the correct text, but the lambdas reference only the final values of grid_row and grid_column, so all buttons print "3, 3" when pressed.
The buttons display properly with the correct text, but the lambdas reference only the final values of grid_row and grid_column, so all buttons print "3, 3" when pressed.
from tkinter import * root = Tk() root.title(" ") root.geometry("250x250+0+20") def button_print(row, column): print(f"{row + 1}, {column + 1}") buttons = [] for grid_row in range(3): button_row = [] for grid_column in range(3): button = Button(root, text = f"{grid_row + 1} {grid_column + 1}", command = lambda: button_print(grid_row, grid_column), width = 4, height = 3) button.grid(row = grid_row, column = grid_column, padx = (10, 10), pady = (10, 10)) button_row.append(button) buttons.append(button_row)