【问题标题】:Python Tkinter Toplevel runs without callingPython Tkinter Toplevel 无需调用即可运行
【发布时间】:2014-07-02 14:57:38
【问题描述】:

你好,我有一些非常简单的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()

但是,每次我运行ths脚本时,asktk toplevel和mainparent Tk一起弹出,即使我不按菜单栏,并且焦点设置为asktk。怎么了?

【问题讨论】:

    标签: python tkinter python-2.6


    【解决方案1】:

    试试这个:在有...的行中

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

    把 createnewguiprojectgui 末尾的 () 去掉。也就是说,传递函数,不要调用它。

    下面的行也应该这样......

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

    【讨论】:

      【解决方案2】:

      这里的命令是调用创建新窗口对象 onload 的函数,而不是在选择 New Project 时。

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

      您需要将其更改为:

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

      【讨论】:

      • 谢谢。现在我明白为什么它自己运行了。谢谢你,还有其他答案。
      【解决方案3】:

      不要调用函数command=createnewguiproject()。除掉 ()。你的 createnewguiproject() 方法会在主循环开始后立即被调用。

      这样做:

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

      或者如果你想发送一些参数然后:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多