zewutz
zewutz

Reputation: 31

TypeError: open_file() missing 1 required positional argument: 'self'

I'm creating a notepad as my first GUI project.. I create a toolbar with file and edit cascade menu, with some commands in them. But when I try to open a file or save a file, it gives me this error TypeError: open_file() missing 1 required positional argument: 'self' . But when I use shortcuts like CTRL + O , it works..

Part of my code:

import os,sys
from tkinter import *
import tkinter.messagebox,tkinter.filedialog

class Commands:
    def open_file(self):
        self.my_filetypes = [('all files', '.*'), ('text files', '.txt')]
        self.askPath = tkinter.filedialog.askopenfile(parent=root,
                                              initialdir=os.getcwd(),
                                              title="Open file",
                                              filetypes=self.my_filetypes,
                                              mode="r")
        self.path_f = self.askPath.name
        with open(self.path_f,"r") as file:
            content = file.read()
            notepad.delete("1.0", "end")
            notepad.insert(END,content)

class Window:
    def framesForDays(self):
        #Toolbar frame
        self.toolbarFrame = Frame(root,relief="groove")
        self.toolbarFrame.pack(side="top",fill="both")
        #Text frame
        self.textFrame = Frame(root,relief="groove")
        self.textFrame.pack(side="top",fill="both",expand=True)

    def settings(self):
        self.m = Menu(self.toolbarFrame)
        root.title("Notepad")
        root.config(menu=self.m)

    def subMenu(self):
        self.submenu=Menu(self.m)
        self.m.add_cascade(label='File',menu=self.submenu)
        self.submenu.add_command(label='Open', accelerator="CRTL+O",command=(Commands.open_file)) 
        root.bind_all("<Control-O>", (Commands.open_file)) and root.bind_all("<Control-o>", (Commands.open_file)) 

    def notePad(self):
        global notepad
        notepad = Text(self.textFrame)
        notepad.pack(side="left",expand=True,fill="both")

        #Scroll bar
        scroll_y = Scrollbar(self.textFrame, orient="vertical", command=notepad.yview)
        scroll_y.pack(side="left", expand=False, fill="y")
        notepad.configure(yscrollcommand=scroll_y.set)

root = Tk()

wnd = Window()
wnd.framesForDays()
wnd.settings()
wnd.subMenu()
wnd.notePad()

root.mainloop()

Upvotes: 0

Views: 1214

Answers (1)

Kahn
Kahn

Reputation: 193

Since you define open_file with a self parameter.It requires an instance, called like:

my_object=Commands()
my_object.open_file()
Commands.open_file(my_object)

But in your case,self is not necessary.You can define it as a static method

class Commands:
    @staticmethod
    def open_file():
        ...

Then you can call it without any instance,like:

Commands.open_file()

Upvotes: 3

Related Questions