2017-01-03 18 views
0

单击菜单栏中的选项时,单击时会出现一个新窗口。但是,当主程序开始运行时,新窗口会立即出现,然后单击菜单中的选项。单击选项以在主程序中运行它之前,会出现New Top Level窗口。

窗口只有在单击选项时才会出现,而在主程序开始运行时不会立即出现?

#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() 

回答

2

相反的:

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

尝试:

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

如果你把括号,该功能将被立即执行,而如果你不把他们只将作为对该事件信号执行的函数的引用。

使其更清晰,同样的事情发生,如果你想存储在一个列表的功能,以便以后执行:

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]() 
+0

谢谢TrakJohnson!非常感激! –

相关问题