我正在尝试使用Python 2.7中的tkinter创建一个简单的GUI。昨天它工作得很好,但今天崩溃了一个非常奇怪的错误:
sbar.pack(side=RIGHT, fill=Y)
NameError: name 'RIGHT' is not defined
当我删除参数时,仍然存在另一个非常相似的错误:
menubar=Menu(mgui)
NameError: name 'Menu' is not defined
我不知道为什么会这样,为什么它停止工作。我不确定是不是因为代码错误或者我正在使用的工具。
这是代码:
import Tkinter as tk
import tkMessageBox
from ScrolledText import *
mgui=tk.Tk()
mgui.geometry('700x450')
mgui.title('Adminstrador de ntoas')
mtitle=tk.StringVar()
mtext=tk.StringVar()
sbar = tk.Scrollbar(mgui)
sbar.pack()
menubar=Menu(mgui)
def donothing():
filewin = Toplevel(mgui)
button = Button(filewin, text="Do nothing button")
button.pack()
def llama_crea_notebook():
cng_gui=tk.Toplevel(width=700,height=200)
cng_gui.title("Generado de Notebooks")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Create Notebook", command=donothing)
filemenu.add_command(label="Change Notebook", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Close", command=quit)
menubar.add_cascade(label="File", menu=filemenu)
notemenu = Menu(menubar, tearoff=0)
notemenu.add_command(label="Read Note", command=donothing)
notemenu.add_command(label="Delete Note", command=donothing)
menubar.add_cascade(label="Note", menu=notemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Manual", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
您将tkinter
模块导入为import Tkinter as tk
,这意味着您要从tkinter
访问的所有内容必须以
tk.<something>
Button
,Menu
,RIGHT
......都属于tkinter
。解决方案:用import Tkinter as tk
替换from Tkinter import *
。
但是,使用tk.<something>
更具可读性,因此我建议使用该选项。
你得到这些错误的原因是它们被写成好像有一个:
from Tkinter import *
线。相反,你有一个更可读:
import Tkinter as tk
因此,RIGHT
和Menu
都没有在全局命名空间中定义。使用:
sbar.pack(side=tk.RIGHT, fill=tk.Y)
和
menubar=tk.Menu(mgui)
代替。 Toplevel
和Button
调用还有其他几个类似的问题。