【问题标题】:I keep getting TypeError: count_function() missing 1 required positional argument: 'self'我不断收到 TypeError: count_function() missing 1 required positional argument: 'self'
【发布时间】:2015-03-09 00:23:27
【问题描述】:

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

代码:

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

【问题讨论】:

  • 您的第一个代码块中有错字。 class CounterClass(Frame): 应该有 4 个空格。 SO的编辑器要求我更改6个字符,所以我无法为您进行编辑。

标签: python python-3.x tkinter


【解决方案1】:
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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2022-01-06
    • 2016-05-09
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多