我一直得到TypeError:count_function()缺少1个必需的位置参数:' self'

时间:2015-03-08 16:05:14

标签: python python-3.x tkinter

我正在尝试创建一个小的计数器应用程序,但是当我尝试创建一个让计数器上升的实际按钮时,我似乎陷入了困境。

代码:

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'

但是,当我创建一个应该完全相同的模块,但是我不使用类时,它可以正常工作:

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()

1 个答案:

答案 0 :(得分:3)

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

当您单击该按钮时,这将尝试在没有任何参数的情况下调用count_function。但由于它是一个实例方法,因此需要(隐式)self参数。

要解决此问题,您应该在__init__方法内移动元素的创建。这不仅可以防止它们存储为(共享)类成员,还可以指定绑定方法:

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()