How to Pass Arguments to Tkinter button’s callback Command?
In this tutorial, we are going to see how to pass arguments to Tkinter button’s callback Command? The ‘command’ option of the Button Tkinter widget is triggered when the user presses the button. In some cases, you want to pass arguments to the function associated with the ‘command’ option, but you cannot pass arguments as below:
btn = tk.Button(gui, text="Click here!", command=myFunction(arguments))
We will see how to pass arguments to the action associated with a Button using lambda functions in Python.
How to Pass Arguments to Tkinter button’s callback Command?
You can use the lambda function to create a simple temporary function to call when the button is clicked. The following example changes the text of the button when it is clicked, the new text is received via the ‘str’ parameter.
from tkinter import * #Fonction def changeText(str): btn['text'] = str gui = Tk() gui.geometry('200x100') #Button btn = Button( gui, text = "Click here!", command = lambda: changeText('Welcome to StackHowTo!') ) btn.pack() gui.mainloop()
Output:
