Python NameError:name' frame'未定义(Tkinter)

时间:2014-04-19 23:48:39

标签: python tkinter nameerror

以下是代码:

#!/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 个答案:

答案 0 :(得分:4)

这里有点错误:

  1. 它是__init__,而不是_init_
  2. 您应该了解类成员变量(未在__init__中设置)和实例成员变量(在__init__中设置)之间的区别。您完全错误地使用self
  3. 您的类似乎以递归方式实例化自己??
  4. 你应该分开关注,而不是让一个巨大的无形课程完成整个生命。
  5. 您的错误是由2引起的,但在您查看1和3之前无法完全解决。

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