jwm197
jwm197

Reputation: 79

Assign a value to a button in tkinter

I am writing a chess program where each square is a button. Right now I am writing the command to make the pieces be able to move (which is executed when one is clicked) but it is telling me I am missing an argument (squareposition) when clicking.

How can I bind a value to each button within Game.movepiece ? here is the code I used to create the buttons:

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()

and here is the button's command function:

    def movepiece(self, squareposition):
        if self.square==(-10,-10):
            self.square=squareposition

Upvotes: 1

Views: 51

Answers (1)

PRMoureu
PRMoureu

Reputation: 13347

Game.movepiece(position) is calling the method at the class level, so position is used for the self parameter then squareposition is missing. You need to use an instance of Game to be able to call the method properly. Maybe you already instantiate it elsewhere in your code ?

Then as @Reblochon Masque said you can replace the command with command=lambda pos=position :self.movepiece(pos)

def __init__():
    self.game = Game()

def drawboard(self):
    [...]
    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 pos=position :self.movepiece(pos))

Upvotes: 2

Related Questions