我正在写一个象棋程序,每个方块都是一个按钮。现在,我正在编写一个命令,使工件能够移动(单击时执行),但它告诉我单击时缺少一个参数(squareposition
)
如何将值绑定到Game.movepiece
中的每个按钮?
下面是我用来创建按钮的代码:
def drawboard(self):
x=0
y=0
for column in range(self.n):
self.changecolours()
x=x+1
y=0
for row in range(self.n):
y=y+1
colour = self.colours[self.colourindex]
position=(x,9-y)
buttons=(tk.Button(self.boardframe, padx=10, text=self.placepieces(position), bg=colour, borderwidth=2, relief="solid", font=self.piecefont, command=lambda:Game.movepiece(position) ))
buttons.grid(column=(x-1), row=(y-1), sticky="W"+"E"+"N"+"S" )
self.changecolours()
这是按钮的命令功能:
def movepiece(self, squareposition):
if self.square==(-10,-10):
self.square=squareposition
Game.movepiece(position)
在类级别调用方法,因此position
用于self
参数,然后squareposition
丢失。您需要使用Game
的实例才能正确调用该方法。也许您已经在代码的其他地方实例化了它然后正如@Reblochon Masque所说的,您可以用
command=lambda pos=position :self.movepiece(pos)
替换命令相关问题 更多 >
编程相关推荐