-1

I have two questions concerning python assuming the code below:

  1. Why it is not possible to pass a function with parentheses or parameters to add_command?
  2. What shall I do if my CreateWindow function has to take parameters?

Here's the line of code:

filemenu.add_command(label="update...", command=CreateWindow)
ChiPlusPlus
  • 209
  • 1
  • 6
  • 16
  • What parameters do you want to pass to add windows? – Paul Rooney Jul 06 '15 at 11:33
  • the fields that the windows must have as a start – ChiPlusPlus Jul 06 '15 at 11:38
  • should this be marked as a duplicate? At it's core, this question is just a rephrasing of http://stackoverflow.com/q/5767228/7432 – Bryan Oakley Jul 06 '15 at 14:37
  • I decided not to vote 'close' because, while the answer is a (succinct) duplicate, the question is not, and this one is well phrased in a way that could show up in a search. It is not obvious that ` Nothing happening when I click a Button in tkinter` is about functions versus function calls. – Terry Jan Reedy Jul 10 '15 at 01:21

1 Answers1

8
  1. Doing command=CreateWindow(some_argument) will cause CreateWindow to be executed immediately, and whatever it returns will be used as the parameter for command. Python isn't smart enough to guess that you want CreateWindow to be the callback and not its return value.

  2. Use a lambda expression: filemenu.add_command(label="update...", command=lambda: CreateWindow(some_arguments, go_here))

This is effectively equivalent to:

def f():
     CreateWindow(some_arguments, go_here)

filemenu.add_command(label="update...", command=f)

... But much shorter.

Kevin
  • 74,910
  • 12
  • 133
  • 166