New Top Level window appears before clicking the option to run it in the main program.

230 views Asked by At

When clicking an option in the menu bar, a new window is suppose to appear when clicked. However, the new window is appearing immediately when main program begins to run, before clicking an option in the menu.

How can the window appear only when option is clicked and not immediately when the main program begins to run?

#Main Program

from tkinter import *
from tkinter import ttk
import module

root = Tk()

main_menu_bar = Menu(root)

main_option = Menu(main_menu_bar, tearoff=0)
main_option.add_command(label = "Option 1", command = module.function())
main_menu_bar.add_cascade(label="Main Option", menu=main_option)
root.config(menu=main_menu_bar)

root.mainloop()


#Module
from tkinter import *
from tkinter import ttk

def function ():
    new_window = Toplevel()
1

There are 1 answers

1
TrakJohnson On BEST ANSWER

Instead of:

main_option.add_command(label = "Option 1", command = module.function())

Try:

main_option.add_command(label = "Option 1", command = module.function)

If you put the parentheses, the function will be executed immediately, while if you don't put them it will only be a reference to this function that will be executed upon the event signal.

To make it clearer, the same thing happens if you want to store functions in a list for later execution:

def f():
    print("hello")

a = [f()]  # this will immediately run the function 
           # (when the list is created) and store what 
           # it returns (in this case None)

b = [f]    # the function here will *only* run if you do b[0]()