您好我有一些非常简单的python代码:
from Tkinter import *
from tkFileDialog import askopenfilename
def createnewguiprojectgui():
asktk = Toplevel()
asktk.title("Create new gui source")
Label(asktk, text="Gui options").pack(side=TOP)
askfilename = Entry(asktk)
askfilename.insert(0, "Source name")
askfilename.pack(side=LEFT,fill=X)
yesfornew = Button(asktk, text="cancel", command=createnewguiproject())
nofornew = Button(asktk, text="cancel",command=) #a command
def createnewguiproject():
pass
def main():
mainparent = Tk()
w, h = mainparent.winfo_screenwidth(), mainparent.winfo_screenheight()
mainparent.title("GUI CREATOR")
mainmenu = Menu(mainparent)
filemenu = Menu(mainmenu,tearoff = 0)
filemenu.add_command(label="New project", command = createnewguiprojectgui())
mainmenu.add_cascade(label="File", menu=filemenu)
separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)
mainparent.config(menu=mainmenu)
mainmenu.focus_set()
mainparent.mainloop()
if __name__ == "__main__":
main()
然而,每次我运行脚本时,即使我没有按下菜单栏,问题也会弹出主要的Tk,并且焦点设置为asktk。怎么了?
答案 0 :(得分:2)
试试这个:在......的行中
filemenu.add_command(label="New project", command = createnewguiprojectgui())
将create()从createnewguiprojectgui结束。换句话说,传递函数,不要调用它。
对于以下行也应如此......
yesfornew = Button(asktk, text="cancel", command=createnewguiproject())
答案 1 :(得分:2)
这里的命令是调用创建新窗口对象onload的函数,而不是选择New Project时。
filemenu.add_command(label="New project", command = createnewguiprojectgui())
您需要将其更改为:
filemenu.add_command(label="New project", command = createnewguiprojectgui)
答案 2 :(得分:1)
不要调用函数command=createnewguiproject()
。除掉 ()。主循环开始后立即调用createnewguiproject()
方法。
这样做:
yesfornew = Button(asktk, text="cancel", command=createnewguiproject)
或者,如果你想发送一些参数:
yesfornew = Button(asktk, text="cancel", command=lambda:createnewguiproject(args))