Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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

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()
like image 376
Jason Martin Avatar asked May 08 '17 03:05

Jason Martin


People also ask

What does takes 0 positional arguments but 1 was given?

The Python "TypeError: takes 0 positional arguments but 1 was given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify an argument in a function. Passing an argument to a function that doesn't take any arguments.

How do you use positional arguments in python?

Positional Arguments The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second and the third positional argument listed third, etc. An example of positional arguments can be seen in Python's complex() function.

What are positional arguments?

Positional arguments are arguments that can be called by their position in the function call. Keyword arguments are arguments that can be called by their name. Required arguments are arguments that must passed to the function. Optional arguments are arguments that can be not passed to the function.


1 Answers

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

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.

Adding self to your method definition should resolve the problem.

def generatecode(self):
    pass  # Do stuff here

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
like image 96
Nikolas Stevenson-Molnar Avatar answered Sep 23 '22 16:09

Nikolas Stevenson-Molnar