-1

I want to make a 3x3 button interface. I tried making this on Tkinter but it didn't work right. there is my main.py code:

    frame = tk.Frame(root, bg='white')
    frame.place(relx=0.5, rely=0.5, anchor='center')
    
    buttons = []
    for row in range(3):
        row_list = []
        for col in range(3):
            button = tk.Button(
            master=frame,
            text="",
            font=('Calibri', 36, "bold"),
            fg="black",
            width=5,
            height=2,
            highlightbackground="lightblue",)
            button.config(command=lambda: button_listener(row, col))
    
            button.grid(column=col, row=row, padx=10, pady=10)
            row_list.append(button)
        buttons.append(row_list)
    
    root.mainloop()

and there is my func.py code:

import tkinter as tk

def button_listener(row, col):
    print(f'Button pressed at row:{row}, col:{col}')

when I'm running this code it looks like running successfully but the buttons don't work right. there is the interface: enter image description here

I'll click the first button on the first row. It's printing me "Button pressed at row:2, col:2". It doesn't matter which button I click. it's always printing "Button pressed at row:2, col:2".

1 Answers1

1

Change this:

button.config(command=lambda: button_listener(row, col))

To this:

button.config(command=lambda row=row, col=col: button_listener(row, col))
Pragmatic_Lee
  • 473
  • 1
  • 4
  • 10