[Tkinter-discuss] Help on subclassing - Tkinter.Menu

Michael Lange klappnase at web.de
Sun Sep 13 11:56:20 CEST 2009


On Sat, 12 Sep 2009 18:34:09 -0700 (PDT)
thicket <mark_eastwood at ntlworld.com> wrote:

> #!/usr/bin/env python
> from Tkinter import *
> class MyMenu(Menu):
>         def __init__(self,parent):
>                 Menu.__init__(self,parent, tearoff=0)
>                 self.label1="Mylabel"
>                 self.label2="Myexit"
>         def my_add(self):
>                 self.add_command(label=self.label1,
> command=root.quit)                        
> # did not expect this to work
>                 Menu.add_command(self,label=self.label2,
> command=root.quit)               
> # this I thought may work
> root = Tk()
> menubar = Menu(root)
> menu=MyMenu(menubar)
> menu.my_add()
> menubar.add_cascade(label="Test", menu=menu)
> root.config(menu=menubar)
> mainloop()
> What I would like to do is not hardcode the 'tearoff=0' in the parent
> class constructor i.e. instantiate MyMenu by
> menu=MyMenu(menubar, tearoff=0)

You can achieve this by changing the MyMenu constructor so it will
accept keyword arguments and pass them to the Menu class.

    class MyMenu(Menu):
        def __init__(self,parent, **kw):
            Menu.__init__(self,parent, **kw)

> Also not 100% sure why both add_command() statements in my_add() work?

In your example "root" is defined globally. It would not work if you
put root = Tk() and the following lines inside a function definition
and then the script calls this function.
If you want it to be more obvious you can keep a reference to the
parent inside the MyMenu class, so the constrctor may look like:

    class MyMenu(Menu):
        def __init__(self,parent, **kw):
            Menu.__init__(self,parent, **kw)
            self.parent = parent

However, as long as you need only the quit() method from "root", you
can use self.quit() as well, because any Tkinter widget has a quit()



More information about the Tkinter-discuss mailing list