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.
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.