1

I am using 20 buttons and the when click any one of the button i am calling a "btn_click" function.Is it possible to know the Button name(which button pressed)through that function.Please Find the code snippet below.

    t=['one','two','three','four','five','six','seven','untill to twenty']
    for i in range(1,20):
         obj=Button(root1,text=t[i],command=btn_click,width=27)
         obj.grid(row=i,column=0,sticky=W,padx=15,pady=15) 

1 Answers1

2

You can pass the name of the button as a parameter to the callback function.

def btn_click(button_name):
    print button_name

Then you can create a lambda, passing the current name to the callback.

t = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'untill to twenty']
for i, x in enumerate(t):
     obj = Button(root1, text=x, command=lambda name=x: btn_click(name), width=27)
     obj.grid(row=i, column=0, sticky=W, padx=15, pady=15) 

Note, however, that lambda can behave unexpectedly when used inside a loop, thus the name=x default paramter. Or use functools.partial instead:

     obj = Button(root1, text=x, command=functools.partial(btn_click, x), width=27)
Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179