OK,第一個問題是您聲明瞭下面的代碼:
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()
這是一個起點,肯定能行如下證明:
您可以與周圍的電網probablty渣土()而不是包,並調用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()
國際泳聯L碼:
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()
添加到mgilson的答案,你的縮進是不存在的。 – John
我縮進了你的代碼,以便它在SO上正確渲染。渲染問題的一部分是看起來你有選項卡和空格。 (我將它們全部轉換爲PEP8中指定的每個級別的4個空格)。希望這只是在SO上發佈代碼,但如果沒有,**請不要混合代碼中的製表符和空格**,並且最好像上面所做的那樣對每個縮進級別使用4個空格。 – mgilson