2014-05-14 40 views
0

你好,我有一些非常簡單的Python代碼:Python的Tkinter的Toplevel的運行,而無需調用

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

不過,我每次運行的部份腳本時,asktk頂層彈出與mainparent TK,即使我不按菜單欄,焦點設置爲asktk。怎麼了?

回答

2

命令在這裏呼籲創建一個新的窗口對象的onload,而在選擇新項目比功能。

filemenu.add_command(label="New project", command = createnewguiprojectgui()) 

您需要將其更改爲:

filemenu.add_command(label="New project", command = createnewguiprojectgui) 
+0

謝謝

執行此操作。現在我明白了爲什麼它自己運行。謝謝,還有其他答案。 – user3167683

2

試試這個:在具有行...

filemenu.add_command(label="New project", command = createnewguiprojectgui()) 

採取()關閉createnewguiprojectgui結束。換句話說,傳遞函數,不要調用它。

同樣應該是以下行真的......

yesfornew = Button(asktk, text="cancel", command=createnewguiproject()) 
1

不要調用函數command=createnewguiproject()。去除 ()。一旦主循環啓動,您的createnewguiproject()方法就會被調用。如果你想發送一些參數,那麼

yesfornew = Button(asktk, text="cancel", command=createnewguiproject) 

或者:

yesfornew = Button(asktk, text="cancel", command=lambda:createnewguiproject(args))