Reputation: 1589
I am trying to access the label of a button in Tkinter, when the button is pressed. This involves returning a reference to the target button pressed.
Currently, as I have to input arguments, this is done by binding the command
option to the lambda
function i.e.
button['command'] = lambda: fun_to_call(arg)
Is there any way to return the instance? I have checked the TKDocs and it does not cover. Also, I have tried using a separate list of strings instead to get the label. However, it only returns the last element of the list (I believe this is due to the lambda function not binding the specific element to the list when creating the button instance. I have previously used this list to generate the list of buttons.)
In short, an event-based function bound to the button which returns its parent (the button being pressed).
Upvotes: 2
Views: 1440
Reputation: 2491
def add_callback(control, fun):
def inner():
return fun(control)
control['command'] = inner
...
def test_callback(button):
print "button instance:", button
b = Button(text="click me")
add_callback(b, test_callback)
more declarative:
def with_callback(control, fun):
def inner():
return fun(control)
control['command'] = inner
return control
...
b = with_callback(Button(text="click me"), test_callback)
Upvotes: 3