Creating Menus with Tkinter
Credit: Luther Blissett
Problem
You want to create a window that has a menu bar at the top.
Solution
Use the Tkinter Menu widget:
import sys from Tkinter import * root = Tk( ) # Insert a menu bar on the main window menubar = Menu(root) root.config(menu=menubar) # Create a menu button labeled "File" that brings up a menu filemenu = Menu(menubar) menubar.add_cascade(label='File', menu=filemenu) # Create entries in the "File" menu # simulated command functions that we want to invoke from our menus def doPrint( ): print 'doPrint' def doSave( ): print 'doSave' filemenu.add_command(label='Print', command=doPrint) filemenu.add_command(label='Save', command=doSave) filemenu.add_separator( ) filemenu.add_command(label='Quit', command=sys.exit) root.mainloop( )
Discussion
Menus
in Tkinter applications are handled entirely by the
Menu widget. As shown in the recipe, you use
Menu both for the top-level menu bar (which you
add to a top-level window as its menu
configuration setting) and for cascading menus (which you add to the
menu bar, or to other menus, with the add_cascade
method).
A menu can have several kinds of entries. A
cascade
entry pops up a submenu when the user selects it, and is added with
add_cascade.
A command
entry calls a function when the user selects it, and is added with
add_command.
A
separator visually separates other
entries, and is added with add_separator.
A
checkbutton entry is added with
add_checkbutton and has an associated
Tkinter
IntVar, with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access