Adding a menu to Tkinter
John Posner
jjposner at optimum.net
Mon Oct 26 23:26:40 EDT 2009
Ronn Ross wrote:
> I'm attempting to add a menu bar to my Tkinter app. I can't figure out the correct syntax. Can someone help? I get this error when I run the app:
>
> Traceback (most recent call last):
> File "tkgrid.py", line 26, in <module>
>
> app = App(root)
> File "tkgrid.py", line 10, in __init__
> menubar = Menu(master).grid(row=0)
> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1859, in grid_configure
>
> + self._options(cnf, kw))
> _tkinter.TclError: can't manage ".4300345712": it's a top-level window
>
>
> from Tkinter import *
>
> class App:
>
> def __init__(self, master):
>
>
> def hello():
> print "hello!"
>
> menubar = Menu(master).grid(row=0)
> menubar.add_command(label="Hello!", command=hello)
> Label(master, text="First").grid(row=1)
>
> Label(master, text="Second").grid(row=2)
>
> e1 = Entry(master)
> e2 = Entry(master)
> e3 = Entry(master)
>
> e1.grid(row=0, column=1)
> e2.grid(row=1, column=1)
>
> e2.grid(row=2, column=1)
>
>
> root = Tk()
>
> app = App(root)
>
> root.mainloop()
>
Ronn, I'm not sure what you're trying to accomplish, but it looks like
you're getting wrapped around the axle a bit. Did you want your "App"
object to instantiate a new Tkinter window, in addition to the "root"
window? For that, you'd need to do this:
class App(Toplevel):
...
But maybe you don't really want/need to do that. Here's a template for
creating a single Tkinter window, with a menubar that contains a single
menu item, "File". And clicking the "File" item, opens a submenu with a
single command, "Hello".
#--------------------------
from Tkinter import *
def hello():
print "hello!"
class App(Tk):
def __init__(self):
Tk.__init__(self)
# create a Menu object
mbar = Menu(self)
# set this Menu to be the App window's menu bar
self['menu'] = mbar
# create another Menu object
fileMenu = Menu(mbar)
# set this Menu to be a submenu of the menu bar, under the name "File"
mbar.add_cascade(label="File", menu=fileMenu)
# add a command named "Hello" to the submenu, and have it
# invoke the function "hello"
fileMenu.add_command(label="Hello", command=hello)
app = App()
app.mainloop()
#--------------------------
Note that instead of this:
self['menu'] = mbar
... you could use this:
self.config(menu=mbar)
HTH,
-John
More information about the Python-list
mailing list