1

i have a question when using the Button widget in tkinter. I am new to this. I noticed that when we use the command in the Button widget, sometimes we call a simple function just like that and sometimes we use lambda function and then we call it. What is the difference?

For example: tk.Button(window, text = "Click Me!", command = myfunction) tk.Button(win,text="Result",command=lambda: result(en1.get())

Cant we just use it without lambda? THank you.

1
  • 2
    If you have to pass some arguments to the function, use lambda. Commented Apr 11, 2020 at 2:37

1 Answer 1

2

Use of lambda:

  • The parentheses are the main reason that the function gets executed when given as command to a Button without lambda. If the function(which you are passing to the Button as a command) has no parameters(to be passed to itself), then you can simply pass it as a command avoiding the parentheses(). And hence you don't need to use lambda in this case. Like in this Example:command=func.

  • So using lambda is only necessary when the function has its own parameters(to be passed to itself).Like in this Example:command=lambda:func(a,b,c)

What lambda Does:

  • When you have to pass arguments to the function itself you have cannot avoid parentheses().
  • So in the case of buttons, lambda basically delays the execution of the function until the user clicks the button, by creating another function on the spot, which does not get called until the button is actually clicked. Hence the function does not get executed, where it is given as command to the Button.

Any Questions will be answered.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.