Tkinter menu toplevel or frame

Matimus mccredie at gmail.com
Thu Mar 15 17:09:53 EDT 2007


> Please tell me is here anything that I should change.

The way you have written it, master _must_ be a Toplevel object. So,
maybe parent is the correct name, but it doesn't really matter.

As a side note, there is no reason for this class to inherit Frame.
Aside from packing and sizing the frame, you appear to do nothing else
with it. You could just as easily inherit from object. You should
never make a custom widget that packs itself anyway. A frame object
should act like a frame. What you have made looks more like what I
would call an application class. If you are trying to make a Menu, I
would inherit from that instead.

As an application class (you will still need the new,save... methods
to be defined):

class MyApp(object):
    def __init__(self, master=None):
        if master:
            self.master = master
        else:
            self.master = Tk()

         frame = Frame(master, width=200, height=200)
         frame.pack(fill=BOTH, expand=YES)

         self.makeMenuBar()

     def makeMenuBar(self):
         self.menubar = Menu(self.master)
         self.master.config(menu=self.menubar)

         pulldown = Menu(self.menubar, tearoff=0)
         pulldown.add_command(label='New', command=self.new)
         pulldown.add_command(label='Open', command=self.onOpen)
         pulldown.add_command(label='Save', command=self.save)
         pulldown.add_command(label='Save As', command=self.saveas)
         pulldown.add_separator()
         pulldown.add_command(label='Exit', command=self.onExit)
         self.menubar.add_cascade(label='File', underline=0,
menu=pulldown)

A menu class (this is untested, but it is close to how I would do it):

class MyMenu(Menu):
    def __init__(self, master=None, **kwargs):
        Menu.__init__(self, master, **kwargs):
        self.master = master

        # This is equivalent to self packing, do it outiside of the
widget
        # self.master.config(menu=self.menubar)

        pulldown = Menu(self, tearoff=0)
        pulldown.add_command(label='New', command=self.new)
        pulldown.add_command(label='Open', command=self.onOpen)
        pulldown.add_command(label='Save', command=self.save)
        pulldown.add_command(label='Save As', command=self.saveas)
        pulldown.add_separator()
        pulldown.add_command(label='Exit', command=self.onExit)
        self.add_cascade(label='File', underline=0, menu=pulldown)

You can use this in the application class:

class MyApp(object):
    def __init__(self, master=None):
        if master:
            self.master = master
        else:
            self.master = Tk()

         self.menubar = MyMenu(self.master)
         self.master.config(menu=self.menubar)

         frame = Frame(master, width=200, height=200)
         frame.pack(fill=BOTH, expand=YES)







More information about the Python-list mailing list