14. tk Menu
14.1. Overview
The
tk.Menu widget creates menus in a Tkinter application.It can be used to create:
* a menu bar attached to the main application window,* pull-down submenus,* shortcut (context) menus that appear when the user right-clicks.
To create a menu widget, the general syntax is
(assuming import via "import tkinter as tk"):
- menu_widget = tk.Menu(parent, option=value)
- *
parentis the parent window or anotherMenuwidget.*option=valuespecifies one or more configuration options.
Menus are normally attached to a
tk.Tk window using ``root.config(menu=menubar)`Submenus are attached to another
Menu using add_cascade().---
14.4. Parameter syntax
- menu_widget = tk.Menu(parent, option=value)
Parameters:
- activebackground
- Syntax:
menu_widget.config(activebackground="color")Description: Background color of the item when active or hovered.Default: SystemHighlight
- activeforeground
- Syntax:
menu_widget.config(activeforeground="color")Description: Text color of the item when active or hovered.Default: SystemHighlightText
- background or bg
- Syntax:
menu_widget.config(bg="color")Description: Background color of the menu.
- font
- Syntax:
menu_widget.config(font=("FontName", size, style))Description: Font of the menu items.
- fg or foreground
- Syntax:
menu_widget.config(fg="color")Description: Text color of the menu items.
- tearoff
- Syntax:
menu_widget.config(tearoff=boolean)Description: Whether the menu can be "torn off" into a separate window.Default: 1
Note
tearoff=0 disables the dashed line that allows a menu to be
detached into its own window. Most modern applications set this
option to 0.
14.5. Default options
Code to get the defaults for each menu option is below.
import tkinter as tk
root = tk.Tk()
menu = tk.Menu(root)
for option in menu.keys():
print(f"{option}: {menu.cget(option)}")
root.mainloop()