pythontkintercompiler-errorspycharmtlc

How do i fix this __init__ self.init_window() error


I have begun setting up my GUI using pyCharm but I've come across some errors in compiling, since adding a menu bar.

I've removed all the code relating to the menu bar and it works but it doesn't help as I would like to add a menu bar.

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("GUI")
            self.pack(fill=BOTH, expand=1)

            #quitButton = Button(self, text="Quit", command=self.client_exit)
            #quitButton.place(x=0, y=0)

            menu = Menu(self.master)
            self.master.config(menu=menu)

            file = Menu(menu)
            file.add_command(label='Exit', command=self.client_exit)
            menu.add_cascade(label='File', menu=file)

            edit = Menu(menu)
            edit.add_command(label='Undo')
            menu.add_command(label='Edit', menu=edit)




        def client_exit(self) :
            exit()


root = Tk()
root.geometry("400x350")

app = Window(root)

Solution

  • Firstly, you need to pass menu into another function to create the menu bar. Secondly, use that new variable instead of menu and use add_cascade instead of add_command. Make sure add_cascade is adding the correct menu option.

    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("GUI")
            self.pack(fill=BOTH, expand=1)
            # quitButton = Button(self, text="Quit", command=self.client_exit)
            # quitButton.place(x=0, y=0)
            menu = Menu(self.master)
            # add a new variable called menubar 
            menubar = Menu(menu)
            # pass 'menubar' into your root's config instead of 'menu'
            self.master.config(menu=menubar)
            filemenu = Menu(menubar, tearoff=0)
            filemenu.add_command(label="Exit", command=self.client_exit)
            # call add_cascade on menubar, and pass your filemenu as the menu param
            menubar.add_cascade(label="File", menu=filemenu)
            edit = Menu(menubar, tearoff=0)
            edit.add_command(label="Undo")
            # Again, add_cascade from your menubar.
            menubar.add_cascade(label="Edit", menu=edit)
    
    
        def client_exit(self) :
            exit()
    
    root = Tk()
    root.geometry("400x350")
    app = Window(root)
    root.mainloop()