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?
Which argument is used to set a callback function on a button in Tkinter? Tkinter button command arguments If you want to pass arguments to a callback function, you can use a lambda expression.
Method 1: Pass Arguments to Tkinter Button using the lambda function. Import the Tkinter package and create a root window. Give the root window a title(using title()) and dimension(using geometry()), now Create a button using (Button()).
Callback functions in Tkinter are generally used to handle a specific event happening in a widget. We can add an event callback function to the Entry widget whenever it gets modified. We will create an event callback function by specifying the variable that stores the user input.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With