好的,第一个问题是您已经声明了以下代码:
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root)
root.mainloop()code here
在类本身内部。它应该在外面,所以这是一个缩进问题(可能是缩进的stackoverflow问题?)。
其次,我简化了代码以使其运行
from Tkinter import *
class Application(Frame):
"""A GUI application with three button"""
#create a class variable from the root (master):called by the constructor
def _init_(self, master):
self.master = master
#simple button construction
# create a button with chosen arguments
# pack it after the creation not in the middle or before
def create_widgets(self):
#"""Create three buttons"""
#Create first button
btn1 = Button(self.master, text = "I do nothing")
btn1.pack()
#Create second button
btn2 = Button(self.master, text = "T do nothing as well")
btn2.pack()
#Create third button
btn3=Button(self.master, text = "I do nothing as well as well")
btn3.pack()
#must be outside class definition but probably due to stackoverlow
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root)
#call the method
app.create_widgets()
root.mainloop()
这是一个起点,绝对可以按以下证明工作:
您可能会使用 grid() 而不是 pack 并从 def init构造函数中调用该方法。希望能帮助到你。
此调用方法也有效:
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root).create_widgets() #creates and invokes
root.mainloop()
我最后的尝试也有效:
def __init__(self,master):
self.master = master
self.create_widgets()
其次是:
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root)
root.mainloop()
最终代码:
from Tkinter import *
class Application(Frame):
"""A GUI application with three button"""
def __init__(self,master):
self.master = master
self.create_widgets()
def create_widgets(self):
#"""Create three buttons"""
#Create first buttom
btn1 = Button(self.master, text = "I do nothing")
btn1.pack()
#Create second button
btn2 = Button(self.master, text = "T do nothing as well")
btn2.pack()
#Create third button
btn3=Button(self.master, text = "I do nothing as well as well")
btn3.pack()
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root)
root.mainloop()