2017-01-03 14 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!非常感激! –

相關問題