试图创建一个程序,当你点击按钮(生成代码)时,它从文件中提取一行数据并输出到
TypeError:generatecode()获取0个位置参数,但给出了1
from tkinter import *
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("COD:WWII Codes")
self.pack(fill=BOTH, expand=1)
codeButton = Button(self, text = "Generate Code", command = self.generatecode)
codeButton.place(x=0, y=0)
def generatecode(self):
f = open("C:/Programs/codes.txt", "r")
t.insert(1.0. f.red())
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
当您在类上调用方法时(例如generatecode()在本例中),Python会自动self作为函数的第一个参数传递.所以当你打电话时self.my_func(),它更像是打电话MyClass.my_func(self).
因此,当Python告诉你"generatecode()需要0个位置参数但是给出了1"时,它告诉你你的方法设置为不带参数,但是self当调用方法时参数仍然被传递,所以实际上它正在接受一个论点.
添加self到方法定义应该可以解决问题.
def generatecode(self):
pass # Do stuff here
Run Code Online (Sandbox Code Playgroud)
或者,您可以将方法设为静态,在这种情况下,Python 不会self作为第一个参数传递:
@staticmethod
def generatecode():
pass # Do stuff here
Run Code Online (Sandbox Code Playgroud)
小智 6
我得到了同样的错误:
\n\n\n类型错误:test() 采用 0 个位置参数,但给出了 1 个
\n
当定义没有 and 的实例方法时,self我调用它,如下所示:
class Person:\n # \xe2\x86\x93\xe2\x86\x93 Without "self" \n def test(): \n print("Test")\n\nobj = Person()\nobj.test() # Here\nRun Code Online (Sandbox Code Playgroud)\n因此,我放入self实例方法并调用它:
class Person:\n # \xe2\x86\x93\xe2\x86\x93 Put "self" \n def test(self): \n print("Test")\n\nobj = Person()\nobj.test() # Here\nRun Code Online (Sandbox Code Playgroud)\n然后,错误就解决了:
\nTest\nRun Code Online (Sandbox Code Playgroud)\n另外,即使用 定义了实例方法self,我们也不能直接通过类名调用它,如下所示:
class Person:\n # Here \n def test(self): \n print("Test")\n\nPerson.test() # Cannot call it directly by class name\nRun Code Online (Sandbox Code Playgroud)\n然后,就会出现下面的错误:
\n\n\n类型错误:test() 缺少 1 个必需的位置参数:\'self\'
\n
但是,如果定义实例方法时不带self,我们可以直接通过类名调用它,如下所示:
class Person:\n # \xe2\x86\x93\xe2\x86\x93 Without "self" \n def test(): \n print("Test")\n\nPerson.test() # Can call it directly by class name\nRun Code Online (Sandbox Code Playgroud)\n然后,我们可以得到如下结果,没有任何错误:
\nTest\nRun Code Online (Sandbox Code Playgroud)\n详细地,我在What is an "instance method" in Python? 的回答中解释了实例方法。并在我对@classmethod vs @staticmethod in Python 的回答中解释了 @staticmethod和@classmethod。
\n