【问题标题】:Tkinter GUI problemsTkinter GUI 问题
【发布时间】:2018-02-19 05:07:47
【问题描述】:

我正在从事 项目,但进展并不顺利。
这段代码:

from tkinter import *

def NewFile():
    new = Label(root, text="about \n")
def OpenFile():
    openf = Label(root, text="about \n")
def About():
    about = Label(root, text="about \n")

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open...", command=OpenFile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=About)
body = Label(root, text="")
mainloop()

不能按我的需要工作。
当您单击 file > newfile > openhelp > about 时,它应该会编写相应的消息。

它什么都不做

我怎样才能让它做想要的?

【问题讨论】:

    标签: github python tkinter menu


    【解决方案1】:
    from Tkinter import *
    
    
    
    root = Tk()
    menu = Menu(root)
    root.config(menu=menu)
    filemenu = Menu(menu)
    my_label = Label(root, text="Select Menu")
    my_label.place(x=10,y=10)
    
    def my_command(query):
        my_label.config(text=query)
    
    menu.add_cascade(label="File", menu=filemenu)
    filemenu.add_command(label="New", command=lambda x = "New":my_command(x))
    filemenu.add_command(label="Open...", command=lambda x = "Open...":my_command(x))
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=root.destroy)
    
    helpmenu = Menu(menu)
    menu.add_cascade(label="Help", menu=helpmenu)
    helpmenu.add_command(label="About...", command=lambda x = "About...":my_command(x))
    body = Label(root, text="")
    mainloop()
    

    @Lafexlos 是正确的。 您可以在GUI 设计上使用所有python 类型(list、dict、var 等...),最重要的是how to manage all GUI elements,所以都需要一个可访问的状态。

    不要 destroy 任何 GUI 元素,更改并重用它。

    不要在mainloop 中包含任何外部命令(例如:文件、网络等)

    所有 GUI 应用程序都需要 3 个关键部分:INIT >> BUILD >> RUN 否则你会很痛苦。

    使用 GUI 元素 text 作为 variable,当然如果所有元素都可以访问!

    我希望有帮助并接受@Lafexlos 的回答不是我的! 此代码适用于 Python2.7

    【讨论】:

      【解决方案2】:

      您没有在您的小部件上使用几何管理器(pack/grid/place),因此 tkinter 不会向您显示这些。

      此外,您可以在全局范围内创建所有三个标签并在点击时打包并忘记,或者只创建一个标签并根据需要更改其值,而不是在每次点击时创建新标签。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多