IAskQuestions
IAskQuestions

Reputation: 45

tkinter what constructor arguments to use for main class App(tk.Tk)?

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

Upvotes: 0

Views: 575

Answers (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()

Upvotes: 1

Related Questions