类型错误:generatecode() 采用 0 个位置参数,但给出了 1 个 [英] TypeError: generatecode() takes 0 positional arguments but 1 was given

查看:31
本文介绍了类型错误:generatecode() 采用 0 个位置参数,但给出了 1 个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() 需要 0 个位置参数,但给出了 1 个

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

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

推荐答案

当你在一个类上调用一个方法时(比如本例中的generatecode()),Python会自动通过self 作为函数的第一个参数.所以当你调用 self.my_func() 时,更像是调用 MyClass.my_func(self).

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

因此,当 Python 告诉您generatecode() 接受 0 个位置参数但给出了 1 个"时,它告诉您您的方法设置为不接受任何参数,但 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 self argument is still being passed when the method is called, so in fact it is receiving one argument.

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

Adding self to your method definition should resolve the problem.

def generatecode(self):
    pass  # Do stuff here

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

Alternatively, you can make the method static, in which case Python will not pass self as the first argument:

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

这篇关于类型错误:generatecode() 采用 0 个位置参数,但给出了 1 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆