单击菜单栏中的选项时,单击时会出现一个新窗口。但是,在主程序开始运行之前,在单击菜单中的选项之前,新窗口会立即显示。
如果单击选项时窗口如何显示,而主程序何时开始运行则不会立即显示?
#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()
答案 0 :(得分: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]()