Python,Instance没有属性

时间:2015-10-26 13:26:23

标签: python

所以我现在正在尝试学习python,并且我正在关注youtube上的这个指南。它让我了解了这一点。但是当我运行它时我得到了错误:

Traceback (most recent call last):
  File "C:/Users/Frederik/Desktop/test.py", line 29
    app = Application(root)
  File "C:/Users/Frederik/Desktop/test.py", line 11, in __init__
    self.create_widgets()
AttributeError: Application instance has no attribute 'create_widgets'

这是我的代码:

from Tkinter import *

class Application(Frame):
""" GUI with click counter """

  def __init__(self, master):
    """ Init the frame """
    Frame.__init__(self,master)
    self.grid()
    self.button_clicks =0 #Counts the button clicks
    self.create_widgets()

    def create_widgets(self):
        """ Create button widget """
        self.button = Button(self)
        self.button["text"] = "Total Clicks: 0"
        self.button["command"] = self.update_count
        self.button.grid()

        def update_count(self):
            """ Increase click count """
            self.button_clicks += 1
            self.button["text"] = "Total Clicks: " + str(self.button_clicks)

root = Tk()
root.title("Button Counter")
root.geometry("200x100")

app = Application(root)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

正如Mathias评论的那样,问题在于你的缩进。 Python需要适当的缩进,因为它决定了块的开始和结束。

以下是您的代码的外观:

from Tkinter import *

class Application(Frame):
    """ GUI with click counter """

    def __init__(self, master):
        """ Init the frame """
        Frame.__init__(self,master)
        self.grid()
        self.button_clicks =0 #Counts the button clicks
        self.create_widgets()

    def create_widgets(self):
        """ Create button widget """
        self.button = Button(self)
        self.button["text"] = "Total Clicks: 0"
        self.button["command"] = self.update_count
        self.button.grid()

    def update_count(self):
        """ Increase click count """
        self.button_clicks += 1
        self.button["text"] = "Total Clicks: " + str(self.button_clicks)

root = Tk()
root.title("Button Counter")
root.geometry("200x100")

app = Application(root)

root.mainloop()