0

Ok, so I have this code that generates a grid of buttons:

def click():

    squares[-1][y].configure(bg='blue')

def game(width,height):

    global squares
    squares = []

    global y

    for x in range(width):

        squares.append([0] * height)

        for y in range(height):

            squares[-1][y] = Button(gameWindow,command=click)
            squares[-1][y].grid(column = x, row = (y + 1), sticky =(N+S+E+W))

    for x in range(width):

        Grid.columnconfigure(gameWindow, x, weight = 1)

    for y in range(height):

        Grid.rowconfigure(gameWindow, (y + 1), weight = 1)

    gameWindow.mainloop()

game(8,8)    

I can configure a specific button (1,1) by doing this:

squares[1][1].configure(bg='blue')

But when I try to configure a button when it is used, it changes the button in the bottom right.

Any help would be greatly appreciated, thanks in advance.

Ollie Mills
  • 5
  • 1
  • 2
  • 1
    Please provide a [mcve]. Specifically: what happens and what you expected to happen. –  Jan 17 '17 at 19:45
  • you have `for y in range(height)` so after this loop `y == height-1`. And you do `squares[-1][y].configure(bg='blue')` so you use `squares[-1][height-1]` – furas Jan 17 '17 at 20:12
  • you need `Button(gameWindow, command=lambda arg=y:click(arg))` and `def click(arg): squares[-1][arg].config(bg='blue')` – furas Jan 17 '17 at 20:14
  • Possible duplicate of [How to change button color with tkinter](http://stackoverflow.com/questions/5543815/how-to-change-button-color-with-tkinter) – darrenvba Jan 18 '17 at 08:47

1 Answers1

1

You have loop

for y in range(height):

so after this loop y is equal height-1.

When you click button then it uses squares[-1][y] but y = height-1 so you use always squares[-1][height-1]

You have to assing to button function with argument - button number - using lambda.
But if you use lambda inside for then you can't do directly lambda:click(y)
but you need lambda arg=y:click(arg)

 Button(gameWindow, command=lambda arg=y:click(arg))

And function has to get this argument and use it

 def click(arg): 
      squares[-1][arg].config(bg='blue')
furas
  • 134,197
  • 12
  • 106
  • 148