我试图执行我的第一个tkinter应用,但是它给了我错误,如下所示。不知道为什么'框架'对于同一个类的函数是不可见的?
Traceback (most recent call last):
File "C:\Data\Personal\Python\Tkinter\GUI_ver1.py", line 25, in <module>
myapp = App(root)
File "C:\Data\Personal\Python\Tkinter\GUI_ver1.py", line 7, in __init__
self.createWidgets()
File "C:\Data\Personal\Python\Tkinter\GUI_ver1.py", line 10, in createWidgets
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
NameError: global name 'frame' is not defined
我的计划如下:
from Tkinter import *
class App(Frame):
def __init__(self, master=None):
frame = Frame(master)
frame.pack()
self.createWidgets()
def createWidgets(self):
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
self.hi_there.pack({"side": "right"})
def say_hi(self):
print "hi there, everyone!"
root = Tk()
# create the application
myapp = App(root)
myapp.master.title("My First App")
myapp.master.geometry('450x130')
myapp.master.resizable(0,0)
# start the program
root.mainloop()
答案 0 :(得分:3)
def __init__(self, master=None):
frame = Frame(master)
frame.pack()
self.createWidgets()
您在frame
中定义的__init__
在任何其他方法中都不可见。如果您希望能够访问它,则需要将其设为self
。
def __init__(self, master=None):
self.frame = Frame(master)
self.frame.pack()
self.createWidgets()
每当您使用变量时,请不要忘记包含self.
。
def createWidgets(self):
self.button = Button(self.frame, text="QUIT", fg="red", command=self.frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(self.frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
这是解决NameError的最简单方法,但您的代码仍会因AttributeError: App instance has no attribute 'master'
错误而崩溃。发生这种情况的原因是,虽然您将App
作为Frame
的子类,但您从不为它调用Frame
初始值设定项,因此当您尝试调用Frame方法时会感到困惑。请记得致电__init__
。
def __init__(self, master=None):
Frame.__init__(self, master)
frame = Frame(master)
frame.pack()
self.createWidgets()
最后一次添加,你的代码应该正常工作,但它比它需要的复杂一点。您的App
实例是一个框架,但它本身也包含一个框架self.frame
。您可以通过删除第二帧并直接将小部件添加到self
来简化此操作。
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.button = Button(self, text="QUIT", fg="red", command=self.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(self, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
self.hi_there.pack({"side": "right"})