Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my command function not being called when I press a button?

I’m a bit of a newbie to Tkinter, so bear with me. I’m making a simple game which involves buttons laid out in a grid. When one of these buttons is press, depending on their position, they move to a different spot on the grid. I feel like the mistake is probably a really small one but it continues to escape me.

All code relevant to the issue:

import numpy as np
from tkinter import *

class MoveableButton(Button):
    def __init__(self, location, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.location = location
    
    # the function I hope to call
    def move(self):
        self.location = "new location"
        self.grid(column=self.location[0], row=self.location[1])

root = Tk()
pieces = [MoveableButton("location_coordinates", root) for i in range(24)]
for i, piece in enumerate(pieces):
    piece.command = piece.move #the source of the problem

[piece.grid(column=i%5, row=i//5) for i, piece in enumerate(pieces)]
root.mainloop()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you never assign a command to the button. You set the command attribute on the python object, but that’s not the same as setting the option for the actual widget.

You need to remove piece.command = piece.move and add piece.configure(command=piece.move)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading