prettyfrustrated
prettyfrustrated

Reputation: 3

How to get the variable name of a button I have just clicked, tkinter

I am currently programming a game with a field of buttons, each with a unique variable name. Each button is part of a class "Space" with several attributes. Each button has the same command associated with it: "move()". When I click a button, I want the code to get the attributes of that specific button using a ".getM()" function. My code for move is below, it is not complete. How do I assign the button name to var.?

def move():
    var = "???????"
    mGridv = var.getM()
    iGridv = var.getI()
    playv = var.getPlay()

    if playv != None:
        message = "This play is invalid"

Upvotes: 0

Views: 5667

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386010

Assuming you're creating buttons in the usual way, you can use lambda to pass arguments. lambda lets you create an anonymous function with arguments, that you can then use to call your function.

If you want to pass the actual button reference, you will need to do it in two steps, since the button object won't exist until after it is created.

for i in range(10):
    button = tk.Button(...)
    button.configure(command=lambda b=button: move(b))

Your move function would need to look like this:

def move(var):
    mGridv = var.getM()
    iGridv = var.getI()
    ...

You don't necessarily have to pass in an instance of the button, you could also pass in the attributes of that button.

Upvotes: 1

joaquin
joaquin

Reputation: 85603

You can Bind the button event to the function.

from Tkinter import *

def move(event):
    """will print button property _name"""
    w = event.widget                      # here we recover your Button object
    print w._name

root = Tk()

but_strings = ['But1', 'But2', 'But3']    # As many as buttons you want to create
buttons = []                              # let's create buttons automatically
for label in but_strings:                 # and store them in the list 'buttons'
    button_n = Button(root, text=label)
    button_n.pack()
    button_n.bind('<Button-1>', move)     # here we bind the button press event with
                                          #  the function 'move()' for each widget
    buttons.append(button_n)

root.mainloop() 

Upvotes: 0

Related Questions