pl4gue
pl4gue

Reputation: 3

Issues with Tkinter OOP Menubar

I am trying to write a simple OOP window with a menubar in Python using Tkinter. I can do exactly what I want to with procedural programming but I am running into hiccups trying to wrap it up in classes. This is a small snippit:

from Tkinter import *

class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.initUI()


    def initUI(self):
        self.parent.title("Example")
        self.pack(fill=BOTH, expand = 1)

        """ Menu Bar """

        self.menubar = Menu(self)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label = "Open", command = None)
        self.filemenu.add_command(label = "Save", command = None)
        self.filemenu.add_command(label = "Save As", command = None)
        self.filemenu.add_command(label = "Close", command = None)

        self.filemenu.add_separator()

        self.filemenu.add_command(label = "Exit", command = None)
        self.menubar.add_cascade(label = 'File', menu = self.filemenu)
        self.config(menu = self.menubar)



def main():
    root = Tk()
    root.geometry("800x600+300+300")
    app = App(root)
    root.mainloop()

if __name__ == '__main__':
    main()

When I run this, I get this error:

Traceback (most recent call last):
  File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 39, in <module>
    main()
  File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 35, in main
    app = App(root)
  File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 8, in __init__
    self.initUI()
  File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 28, in initUI
    self.config(menu = self.menubar)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1262, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1253, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-menu"

Any one care to help a noob out?

Upvotes: 0

Views: 787

Answers (1)

sPaz
sPaz

Reputation: 954

In TKinter, You are supposed to add menubar to the root since it should be over any toplevel windows. i.e. In this case,

self.parent.config(menu = self.menubar)

Upvotes: 1

Related Questions