-1

I am trying to create a grid of buttons using python tkinter. And I create a 8X8 list to put the buttons. And then I want to update the text of a clicked button. I tried by passing arguments, but failed

from tkinter import *
import tkinter.font as tkFont

root = Tk()
font = tkFont.Font(family="helvetica", size=12)
frame=Frame(root)
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0, sticky=N+S+E+W)
grid=Frame(frame)
grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
Grid.rowconfigure(frame, 7, weight=1)
Grid.columnconfigure(frame, 0, weight=1)

btn = []
for i in range(8):
    temp = []
    for j in range(8):
        bt = None
        temp.append(bt)
    btn.append(temp)

def action(x,y):
    value = 0
    print(x,y)
    btn[x][y].configure(text=value ,font=font)

#example values
for x in range(8):
    for y in range(8):
        print(x,y)
        btn[x][y] = Button(frame,width=4,height=2, command= lambda: action(x,y))
        btn[x][y].grid(column=x, row=y, sticky=N+S+E+W)

for x in range(8):
  Grid.columnconfigure(frame, x, weight=1)

for y in range(8):
  Grid.rowconfigure(frame, y, weight=1)

root.mainloop()

whatever button I click it is updating (7,7) button

  • It prints and updates (7,7) as _x_ and _y_ are both 7 at the end of your button nested loops. Use a new value (or state) for each button and use `if...elif` to toggle through your buttons – FrainBr33z3 Jun 25 '19 at 05:39

1 Answers1

0

You must pass the two arguments to the lambda function:

like this:

btn[x][y] = Button(frame, width=4, height=2, command=lambda x=x, y=y: action(x, y))
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80