Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 40 ยท Dialogs and Menus

Menus, Context Menus and Menubuttons in Tkinter

Build a Tkinter menu bar with File and Edit menus, checkbutton and radiobutton items, keyboard shortcuts, right-click context menus and Menubutton widgets.

A menu bar is how desktop applications keep dozens of commands out of the way: File, Edit, View, Help. Tkinter's Menu widget builds three things with the same class: the menu bar across the top of a window, the drop-down lists under it, and pop-up menus that appear on a right click. A related widget, Menubutton, puts a drop-down menu behind an ordinary-looking button.

All Tkinter code on this page is read-only because it needs a display. Next to it you get runnable stand-ins: a declarative menu description that you can print and test, and the state logic of checkbutton and radiobutton items.

A menu bar with drop-downs

Python
import tkinter as tk

root = tk.Tk()
root.title("Menus")

menubar = tk.Menu(root)
root.config(menu=menubar)             # attach the bar to the window

file_menu = tk.Menu(menubar, tearoff=False)
file_menu.add_command(label="New", command=new_file, accelerator="Ctrl+N")
file_menu.add_command(label="Open...", command=open_file, accelerator="Ctrl+O")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=file_menu)

root.mainloop()

The window gets a bar with "File" at its top left (on macOS the bar lives at the top of the screen). Clicking File opens a list with New, Open..., a thin separator line and Exit. The key facts:

  • A drop-down is a Menu whose master is the menu bar. Create it with tk.Menu(menubar, ...); the parent matters.
  • tearoff=False removes the dashed line at the top of the list that lets the user detach the menu. It is a relic on Windows and macOS, and without it the first item has index 1 instead of 0.
  • add_cascade hangs a sub-menu under a label. Use it for the bar entries and for sub-menus inside menus.
  • command= takes a function (no parentheses). Use functools.partial or a lambda to pass arguments.
  • accelerator="Ctrl+O" is only text displayed on the right. It does not create the shortcut.

Making shortcuts really work

To make Ctrl+O do something, bind the key sequence yourself. The handler receives an event argument, the menu command does not, so write a small wrapper:

Python
root.bind("<Control-o>", lambda event: open_file())
root.bind("<Control-n>", lambda event: new_file())

Pressing Ctrl+O now calls open_file just like the menu item. On macOS the menu key is Command, so use <Command-o> or define the accelerator per platform. The Events and Bindings chapter explains key sequences in detail; Structuring Tkinter Apps with Classes shows where such bindings live in a bigger program.

Underlined letters (underline=0 puts an underline under the first character) enable Alt-key navigation on Windows and Linux. Use them sparingly; they are a convention, not a requirement.

Checkbutton and radiobutton items

Menus can hold items that remember a choice. They are tied to Tkinter variables:

Python
view_menu = tk.Menu(menubar, tearoff=False)

show_status = tk.BooleanVar(value=True)
view_menu.add_checkbutton(label="Status bar", variable=show_status, command=toggle_status)

theme = tk.StringVar(value="light")
view_menu.add_radiobutton(label="Light", variable=theme, value="light", command=apply_theme)
view_menu.add_radiobutton(label="Dark", variable=theme, value="dark", command=apply_theme)

menubar.add_cascade(label="View", menu=view_menu)

"Status bar" shows a check mark while show_status is true. Clicking it flips the variable and then runs toggle_status. The two radio items share one StringVar: selecting one sets the variable to its value and the other loses its dot, so exactly one theme is selected. The command runs after the variable changed, so the callback reads the new value with theme.get().

Disabling and changing items

Items are addressed by index (starting at 0 when tearoff=False) or by label:

Python
file_menu.entryconfig("Open...", state="disabled")
file_menu.entryconfig(0, label="New document")
file_menu.delete(2)                 # remove one item
count = file_menu.index("end")      # index of the last item

Disable commands that cannot work now (Save with no changes, Copy with no selection) and enable them when the state changes. Disabled items are grayed out and ignore clicks. A menu can also be rebuilt from scratch with menu.delete(0, "end"), which is how "Open Recent" lists are made.

Context (right-click) menus

A context menu is a Menu that you show yourself at the mouse position with tk_popup:

Python
context = tk.Menu(root, tearoff=False)
context.add_command(label="Cut", command=lambda: text.event_generate("<<Cut>>"))
context.add_command(label="Copy", command=lambda: text.event_generate("<<Copy>>"))
context.add_command(label="Paste", command=lambda: text.event_generate("<<Paste>>"))

def show_context(event):
    try:
        context.tk_popup(event.x_root, event.y_root)
    finally:
        context.grab_release()

text.bind("<Button-3>", show_context)       # right button on Windows and Linux
text.bind("<Button-2>", show_context)       # right button on macOS (also Control-click)

Right-clicking the text area opens a small Cut/Copy/Paste list at the pointer. x_root and y_root are screen coordinates, which is what pop-up placement needs. The grab_release() in finally stops the menu from capturing the mouse if it closes abnormally on some platforms. Sending the virtual events <<Cut>>, <<Copy>> and <<Paste>> reuses the widget's built-in clipboard handling.

A Menubutton is a button that opens a menu below it; useful in toolbars:

Python
mb = tk.Menubutton(toolbar, text="Sort by", relief="raised")
mb.menu = tk.Menu(mb, tearoff=False)
mb["menu"] = mb.menu
mb.menu.add_command(label="Name", command=sort_by_name)
mb.menu.add_command(label="Date", command=sort_by_date)
mb.pack(side="left")

For the common "choose one of these values" case, tk.OptionMenu(root, var, "Small", "Medium", "Large") creates the button, the menu and the variable binding in one call. The modern themed alternative is the combo box (Themed Widgets).

Describing menus as data

Large programs do not write fifty add_command lines by hand. They keep the menu structure in a list or dict and build it in a loop. That structure is plain Python and easy to test. This block is not Tkinter: it prints a menu tree from a declarative description and finds the commands that have accelerators.

Python Stand-in: a menu described as data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The shortcut table is what you would loop over to call root.bind, so menu labels and key bindings can never disagree.

Checkbutton and radiobutton state

Menu variables behave like small state cells. The stand-in below reproduces the "exactly one radio selected" rule and the "command after variable" order:

Python Stand-in: radio and check items share a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Forgetting root.config(menu=menubar): the menu exists but is never shown.
  • Writing command=open_file() instead of command=open_file. The function then runs once at start-up and the item does nothing.
  • Creating the sub-menu with the wrong master (for example tk.Menu(root)). It may still show, but it can behave oddly on macOS.
  • Counting indexes from 0 while tearoff is still on; with the tear-off line, the first real item has index 1.
  • Believing accelerator= creates a shortcut.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does accelerator="Ctrl+S" on a menu item do?

    The accelerator option is a label. Use root.bind('<Control-s>', ...) to make the shortcut work.
  2. 2. Why is tearoff=False usually passed?

    Without it, the menu starts with a tear-off entry and item indexes shift by one.
  3. 3. How is a right-click context menu displayed?

    You bind the right mouse button and pop the menu up at the pointer's screen coordinates.
  4. 4. Which widget keeps radio items in a menu mutually exclusive?

    Radio items write their own value into the shared variable, so only the matching item shows as selected.

Summary

  • Create tk.Menu(root), attach it with root.config(menu=...), and add drop-downs with add_cascade.
  • Pass tearoff=False; use add_command, add_separator, add_checkbutton and add_radiobutton.
  • accelerator is a label; bind the real shortcut with bind.
  • Context menus use tk_popup from a mouse binding.
  • Describe big menus as data and build them in a loop.

Next: Toplevel Windows and Custom Dialogs