[英]Python, tkinter: How to change color of button on press?
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:我可以通过执行以下操作来配置特定按钮 (1,1):
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
.所以在这个循环之后y
等于height-1
。
When you click button then it uses squares[-1][y]
but y = height-1
so you use always squares[-1][height-1]
当你点击按钮时,它使用squares[-1][y]
但y = height-1
所以你总是使用squares[-1][height-1]
You have to assing to button function with argument - button number - using lambda
.您必须使用参数 - 按钮编号 - 使用lambda
分配按钮功能。
But if you use lambda
inside for
then you can't do directly lambda:click(y)
但是如果你在里面使用lambda
for
那么你不能直接做lambda:click(y)
but you need lambda arg=y:click(arg)
但你需要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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.