15

I got 2 buttons, respectively named 'ButtonA', 'ButtonB'. I want the program to print 'hello, ButtonA' and 'hello, ButtonB' if any button is clicked. My code is as follows:

def sayHi(name):
    print 'hello,', name

root = Tk()
btna = Button(root, text = 'ButtonA', command = lambda: text)
btna.pack()

When I click ButtonA, error occurs, text not defined.

I understand this error, but how can I pass ButtonA's text to lambda?

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
Synapse
  • 1,574
  • 6
  • 18
  • 19
  • 2
    possible duplicate of [passing argument in python Tkinter button command](http://stackoverflow.com/questions/6920302/passing-argument-in-python-tkinter-button-command). The other happened 5 hours before by another user. Amazing coincidence! – Ciro Santilli OurBigBook.com Jan 15 '14 at 11:07

2 Answers2

29

This should work:

...
btnaText='ButtonA'
btna = Button(root, text = btnaText, command = lambda: sayHi(btnaText))
btna.pack()

For more information take a look at Tkinter Callbacks

Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
3

text is not a function in your case. Just have it as:

value = 'ButtonA'
btna = Button(root, text = value, command = lambda: sayHi(value))

And you will get that working.

Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131