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()
Kenil Vasani
When you call a method on a class (such as
generatecode()
in this case), Python automatically passesself
as the first argument to the function. So when you callself.my_func()
, it’s more like callingMyClass.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.Alternatively, you can make the method static, in which case Python will not pass
self
as the first argument: