Why are functions running before they are called?

Question:

I am making a python script:

import tkinter

def print_the_nothing_thing():
    print("I told you, nothing means nothing. For further assistance, please see:")
    print("https://www.youtube.com/watch?v=3WNlWyFgLCg")
    print("Type the url into the browser.")

#setup the window
window = tkinter.Tk()
menu = tkinter.Menu(window)
window.configure(menu=menu)
view = tkinter.Menu(menu)
file = tkinter.Menu(menu)
menu.add_cascade(label="File", menu=file)
menu.add_cascade(label="View", menu=view)
#here is my problem
view.add_command(label="Nothing here!", command=print_the_nothing_thing())
file.add_command(label="Nothing here!", command=print_the_nothing_thing())
helpm.add_command(label="Help", command=helpy())
window.mainloop()

My problem is that when I define the function, it runs the function first. After closing it, the menu command does nothing.

Asked By: user5673236

||

Answers:

You need to remove () from those add_command lines, like

view.add_command(label="Nothing here!", command=print_the_nothing_thing)
file.add_command(label="Nothing here!", command=print_the_nothing_thing)

You are calling those functions there, and they return None. If you use just the name of the function, you get a function object.

Answered By: J.J. Hakala

You’re calling the function in add_command:

view.add_command(label="Nothing here!", command=print_the_nothing_thing())
file.add_command(label="Nothing here!", command=print_the_nothing_thing())
helpm.add_command(label="Help", command=helpy())

Instead, point add_command to the function name; don’t execute it.
Thus:

view.add_command(label="Nothing here!", command=print_the_nothing_thing)
file.add_command(label="Nothing here!", command=print_the_nothing_thing)
helpm.add_command(label="Help", command=helpy)
Answered By: user707650
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.