Python NameError: 名称 'frame' 未定义 (Tkinter)
这是代码:
#!/usr/bin/python
from tkinter import *
class App:
def _init_(self, master):
frame = Frame(master)
frame.pack()
self.lbl = Label(frame, text = "Hello World!\n")
self.lbl.pack()
self.button = Button(frame, text="Quit", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Say hi!", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print("Hello!")
root = Tk()
root.title("Hai")
root.geometry("200x85")
app = App(root)
root.mainloop()
然后,这里是错误信息:
Traceback (most recent call last):
File "F:/HTML/HTMLtests/python/hellotkinter2.py", line 4, in <module>
class App:
File "F:/HTML/HTMLtests/python/hellotkinter2.py", line 10, in App
self.lbl = Label(frame, text = "Hello World!\n")
NameError: name 'frame' is not defined
不知道哪里出错了!非常感谢任何帮助!
2 个回答
1
缩进和大写字母有点问题,还有一些下划线。下面的代码可以正常运行。
#!/usr/bin/python
from Tkinter import *
class App(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.lbl = Label(frame, text = "Hello World!\n")
self.lbl.pack()
self.button = Button(frame, text="Quit", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Say hi!", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print("Hello!")
root = Tk()
root.title("Hai")
root.geometry("200x85")
app = App(root)
root.mainloop()
4
这里有几个问题:
- 应该是
__init__
,而不是_init_
。 - 你需要了解类成员变量和实例成员变量的区别。类成员变量是在
__init__
之外定义的,而实例成员变量是在__init__
中设置的。你对self
的使用完全错误。 - 你的类似乎在不断地自己创建自己??
- 你应该把不同的功能分开,而不是把所有东西都放在一个巨大的、没有具体形状的类里。
你的错误主要是因为第二点,但在你解决第一点和第三点之前,这个问题不会完全解决。