以下是代码:
#!/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
找不到它出错的地方!感谢任何帮助!
答案 0 :(得分:4)
这里有点错误:
__init__
,而不是_init_
。__init__
中设置)和实例成员变量(在__init__
中设置)之间的区别。您完全错误地使用self
。您的错误是由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()