I keep getting TypeError: count_function() missing 1 required positional argument: 'self'

I keep getting TypeError: count_function() missing 1 required positional argument: 'self'

我正在尝试创建一个小计数器应用程序,但在尝试创建一个使计数器上升的实际按钮时似乎卡住了。

代码:

from tkinter import *

class CounterClass(Frame):
    buttonFrame = Frame(height=200, width=200)
    counterStatus = Label(buttonFrame, text="0")

    def count_function(self):
        i = int(self.counterStatus.cget("text"))
        i += 1
        self.counterStatus.config(text=str(i))
    counter = Button(buttonFrame, text="+1", command=count_function)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.buttonFrame.pack()
        self.counterStatus.pack()
        self.counter.pack()

if __name__ == "__main__":
    root = Tk()
    c = CounterClass(master=root)
    c.mainloop()
    root.destroy()

当我点击按钮时,出现了这个错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
return self.func(*args)
TypeError: count_function() missing 1 required positional argument: 'self'

然而,当我创建一个应该做完全相同的模块时,但我不使用 class 它工作正常:

from tkinter import *

root = Tk()

def count_function():
    i = int(counterStatus.cget("text"))
    i += 1
    counterStatus.config(text=str(i))

buttonFrame = Frame(height=200, width=200)
counterStatus = Label(buttonFrame, text="0")
counterButton = Button(buttonFrame, text="+1", command=count_function)

buttonFrame.pack()
counterStatus.pack()
counterButton.pack()

root.mainloop()
counter = Button(buttonFrame, text="+1", command=count_function)

当您单击该按钮时,这将尝试不带任何参数地调用 count_function。但由于它是一个实例方法,它需要(隐式)self 参数。

要解决这个问题,您应该将元素的创建移到 __init__ 方法中。这不仅可以防止它们被存储为(共享)class 成员,而且还允许您指定绑定方法:

class CounterClass(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.buttonFrame = Frame(height=200, width=200)
        self.counter = Button(self.buttonFrame, text="+1", command=self.count_function)
        self.counterStatus = Label(self.buttonFrame, text="0")
        self.pack()