0

I know that to call a function when a button is clicked, we write command = name_of_function within the button widget parentheses. But, when we try to pass a value into the function by adding an argument within parentheses after the function name, the function is called too early and not when the button is clicked.

I know that we can use lambda to get around this e.g. command = Lambda: name_of_function(argument).

But what I don't understand is why does lambda work, and not a normal function call with parentheses and arguments?

For example, this works:

editmenu.add_command(label="1. Problem Definition", command=lambda: changeText(0))

but this doesn't:

editmenu.add_command(label="1. Problem Definition", command=changeText(0))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sw123456
  • 3,339
  • 1
  • 24
  • 42

1 Answers1

0

What lambda does is define a new anonymous function which, when it is called, will call your function - so something like:

  api_call(command=lambda: my_function(23))

is very similar to:

  def temp_func():
      my_function(23)

  .....
  .....
  api_call(command=temp_func) 

The main difference is that temp_func is not defined and cannot be easily be reused.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
  • not sure the edit actually added anything, but it did remove a deliberate emphasis on the word "define" - it is definition rather than invocation (calling) which is important here - and hence my emphasis. – Tony Suffolk 66 Sep 23 '14 at 08:08
  • 1
    It may be worth noting the third option, `command=partial(my_function, 23)`. Unlike `lambda`, this at least gives you something useful instead of `` in your tracebacks, and it's less likely to mislead novices into thinking it's an eagle function call. – abarnert Sep 23 '14 at 08:13