2014-04-19 27 views
0

下面是代碼:Python的NameError:名字 '框架' 沒有定義(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 

找不到哪裏出了問題!感謝任何幫助!

回答

4

有相當多的錯在這裏:

  1. __init__,不_init_
  2. 您應該瞭解類成員變量(未在__init__中設置)和實例成員變量(在__init__中設置)之間的差異。你使用self完全錯誤。
  3. 你的類似乎遞歸實例化自己?
  4. 你應該分開關注問題,而不是讓一個巨型無類的課程完成整個課程。

你的錯誤是由於2,但不會徹底解決,直到你看看1和3

1

縮進和大小寫是關閉沿W /一些下劃線。以下作品。

#!/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() 
相關問題