Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass arguments to Tkinter button's callback command?

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?

like image 514
Synapse Avatar asked Aug 03 '11 06:08

Synapse


People also ask

Which argument is used to set a callback function on a button in Tkinter?

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.

How do you pass parameters in button click event in Python?

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()).

What is callback in Tkinter?

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.


2 Answers

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

like image 150
Ocaso Protal Avatar answered Sep 21 '22 17:09

Ocaso Protal


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.

like image 24
Senthil Kumaran Avatar answered Sep 23 '22 17:09

Senthil Kumaran