2017-07-14 79 views
-6

我试图使用python中的Tkinter库使程序没有定义,但它给错误表明---菜单栏在python

NameError:名字“菜单栏”没有定义

import tkinter 
import sys 


def hey(): 
    print("hello") 


def myNew(): 
    mlabel = Label(root,text="yo").pack() 



root = tkinter.Tk() 
root.title("Wizelane") 

root.geometry('400x80+350+340') 
filemenu = tkinter.Menu(menubar, tearoff=0) 
filemenu.add_command(label="New",command=myNew) 

label = tkinter.Label(root,text="say hello") 
label.pack() 
hello = tkinter.Button(root,text="hello",command=hey) 
hello.pack() 
root.mainloop() 
+0

检查这里https://www.tutorialspoint.com/python/tk_menu.htm – babygame0ver

+0

root.mainloop前添加root.config(菜单=菜单栏)线()。可能是工作 – babygame0ver

+3

你期望在这里发生什么?你必须在使用它之前定义变量'menubar'。 –

回答

0

你在这里错过了一些重要的部分。

您需要先配置菜单,并且还需要添加级联标签。

看看这段代码。

import tkinter 

def hey(): 
    print("hello") 

def myNew(): 
    # you forgot to use tkinter.Label here. 
    mlabel = tkinter.Label(root, text="yo").pack() 


root = tkinter.Tk() 
root.title("Wizelane") 
root.geometry('400x80+350+340') 

my_menu = tkinter.Menu(root) 

# configure root to use my_menu widget. 
root.config(menu = my_menu) 

# create a menu widget to place on the menubar 
file_menu = tkinter.Menu(my_menu, tearoff=0) 

# add the File cascade option for drop down use 
my_menu.add_cascade(label = "File", menu = file_menu) 

# then add the command you want to add as a File option. 
file_menu.add_command(label="New", command = myNew) 

label = tkinter.Label(root, text="say hello") 
label.pack() 

hello = tkinter.Button(root, text="hello", command = hey) 
hello.pack() 

root.mainloop()