Tkinter GUI问题

时间:2017-09-11 02:48:24

标签: python tkinter menu

我正在进行一个项目但是进展不顺利 这段代码:

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 时,它会用来编写确认消息。

  

它没有

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

2 个答案:

答案 0 :(得分:1)

您没有在小部件上使用几何管理器(包/网格/地点),因此tkinter不会向您显示这些内容。

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

答案 1 :(得分: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