Tkinter

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:


 
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *