pythonware.com products ::: library ::: search ::: daily Python-URL!
   

Menus

Back   Next   

 Menus

Tkinter provides a special widget type for menus. To create a menu, you create an instance of the Menu class, and use add methods to add entries to it:

  • add_command(label=string, command=callback) adds an ordinary menu entry.

  • add_separator() adds an separator line. This is used to group menu entries.

  • add_cascade(label=string, menu=menu instance) adds a submenu (another Menu instance). This is either a pull-down menu or a fold-out menu, depending on the parent.

Here's an example:

Example 8-1. Creating a small menu

# File: menu1.py

from Tkinter import *

def callback():
    print "called the callback!"

root = Tk()

# create a menu
menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=callback)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)

mainloop()

In this example, we start out by creating a Menu instance, and we then use the config method to attach it to the root window. The contents of that menu will be used to create a menubar at the top of the root window. You don't have to pack the menu, since it is automatically displayed by Tkinter.

Next, we create a new Menu instance, using the menubar as the widget parent, and the add_cascade method to make it a pulldown menu. We then call add_command to add commands to the menu (note that all commands in this example use the same callback), and add_separator to add a line between the file commands and the exit command.

Finally, we create a small help menu in the same fashion.

Back   Next