Python 类型错误:generatecode() 采用 0 个位置参数,但给出了 1 个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43839536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:26:18  来源:igfitidea点击:

TypeError: generatecode() takes 0 positional arguments but 1 was given

pythontkinter

提问by Jason Martin

trying to create a program that when you hit the button(generate code) it extracts a line of data from a file and outputs into the

尝试创建一个程序,当您点击按钮(生成代码)时,它会从文件中提取一行数据并输出到

TypeError: generatecode() takes 0 positional arguments but 1 was given

类型错误: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()

回答by Nikolas Stevenson-Molnar

When you call a method on a class (such as generatecode()in this case), Python automatically passes selfas the first argument to the function. So when you call self.my_func(), it's more like calling MyClass.my_func(self).

当您在类上调用方法时(例如generatecode()在本例中),Python 会自动self作为第一个参数传递给函数。所以当你打电话时self.my_func(),更像是打电话MyClass.my_func(self)

So when Python tells you "generatecode() takes 0 positional arguments but 1 was given", it's telling you that your method is set up to take no arguments, but the selfargument is still being passed when the method is called, so in fact it is receiving one argument.

因此,当 Python 告诉您“generatecode() 接受 0 个位置参数但给出了 1 个”时,它是在告诉您您的方法设置为不接受任何参数,但是在self调用该方法时该参数仍在传递,因此实际上它正在接受一个论点。

Adding selfto your method definition should resolve the problem.

添加self到您的方法定义应该可以解决问题。

def generatecode(self):
    pass  # Do stuff here

Alternatively, you can make the method static, in which case Python will notpass selfas the first argument:

或者,您可以将方法设为静态,在这种情况下 Python不会self作为第一个参数传递:

@staticmethod
def generatecode():
    pass  # Do stuff here