Reputation: 736
I have the code below:
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():
f = open("C:/Programs/codes.txt", "r")
t.insert(1.0. f.red())
root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()
Then, I got the error below:
TypeError: generatecode() takes 0 positional arguments but 1 was given
So, how can I solve the error?
Upvotes: 54
Views: 224989
Reputation: 1
I got the same error:
TypeError: test() takes 0 positional arguments but 1 was given
When defining an instance method without self
and I called it as shown below:
class Person:
# ↓↓ Without "self"
def test():
print("Test")
obj = Person()
obj.test() # Here
So, I put self
to the instance method and called it:
class Person:
# ↓↓ Put "self"
def test(self):
print("Test")
obj = Person()
obj.test() # Here
Then, the error was solved:
Test
In addition, even if defining an instance method with self
, we cannot call it directly by class name as shown below:
class Person:
# Here
def test(self):
print("Test")
Person.test() # Cannot call it directly by class name
Then, the error below occurs:
TypeError: test() missing 1 required positional argument: 'self'
But, if defining an instance method without self
, we can call it directly by class name as shown below:
class Person:
# ↓↓ Without "self"
def test():
print("Test")
Person.test() # Can call it directly by class name
Then, we can get the result below without any errors:
Test
In detail, I explain about instance method in my answer for What is an "instance method" in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.
Upvotes: 8
Reputation: 71
The most upvoted answer does solve this issue,
And just in case anyone is doing this inside of a jupyternotebook. You must restart the kernel of the jupyternotebook in order for changes to update in the notebook
Upvotes: 1
Reputation: 4710
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
Upvotes: 122