0

While trying to learn Python I can across this post

Everything worked well until I moved the function from one class to the other. I created a constructor in the child class and tried to call the newly placed function. Obviously, this didnt work as I had hoped. I narrowed the problems down to calling the constructor. If I use app = App(self) that wont work because its looking for 1 argument, not 2 and if I leave out the arg it causes a recursion where both classes keep calling each other (I think). Right now Im not sure what else to try

Any help you could provide is appreciated.

import tkinter as tk


class MenuBar(tk.Menu):
    def __init__(self, parent):
        tk.Menu.__init__(self, parent)
        app = App(None)  # What needs to be called here?

        fileMenu = tk.Menu(self, tearoff=False)
        self.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="Copy", underline=1, command=app.copy_stuff)
        fileMenu.add_command(label="Exit", underline=1, command=self.quit)


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        menubar = MenuBar(self)
        self.config(menu=menubar)

    def copy_stuff(self):
        print("great")


if __name__ == "__main__":
    app = App()
    app.mainloop()

1 Answers1

1

Try this:

import tkinter as tk


class MenuBar(tk.Menu):
    def __init__(self, parent):
        tk.Menu.__init__(self, parent)
        app = parent

        fileMenu = tk.Menu(self, tearoff=False)
        self.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="Copy", underline=1, command=app.copy_stuff)
        fileMenu.add_command(label="Exit", underline=1, command=self.quit)


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        menubar = MenuBar(self)
        self.config(menu=menubar)

    def copy_stuff(self):
        print("great")


if __name__ == "__main__":
    app = App()
    app.mainloop()
Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39
  • that was it! And after seeing it now, makes total sense but I just couldnt figure it out myself. Thank you very much! – IAskQuestions Aug 29 '21 at 22:41
  • 1
    No problem! Have fun app-developing! – Sylvester Kruin Aug 29 '21 at 22:43
  • This answer would be better if you described what you changed. Otherwise we have to go line-by-line and character-by-character to see what you changed. – Bryan Oakley Aug 29 '21 at 22:45
  • 1
    The only thing I changed was the line in `class MenuBar`: `app = App(None)`, because you already call the app in the second-to-last line. `app = parent` enables you to access the app's `copy_stuff` method by defining the variable `app` that the "copy" command uses to access that method. – Sylvester Kruin Aug 29 '21 at 22:54