Tkinter - Add Icon to Menu Item
Add Icon to Menu Item in Tkinter
In Tkinter, you can add an image as an icon to a menu item on the left or right of the label.
To add an image as an icon to a menu item in Tkinter, create a PhotoImage object with the icon image, and pass it as a value for image parameter when adding the menu item to the menu.
You can specify the position of the icon using compound parameter.
Steps to create Context Menu in Tkinter
In this tutorial, we will consider the following use case.
There is a menu Menu1 in the menu bar. This menu has four items: Item1, and Item2. Item1 has an icon gear-icon.png on its left side.
Step 1
Create menu in the menu bar using Tk.Menu class.
menu_bar = tk.Menu(window)
menu_1 = tk.Menu(menu_bar, tearoff=0)
Step 2
Create PhotoImage object with the image.
item_1_icon = tk.PhotoImage(file="gear-icon.png")
gear-icon.png
Step 3
Specify the image while adding menu item to the menu.
menu_1.add_command(label="Item1", image=item_1_icon, compound="left")
The compound parameter specifies where the image has to be placed relative to the label.
Step 4
Add menu to the menu bar, and the menu bar to the window.
Example
The following is the complete program by combining all the above steps to create and display a context menu when user right clicks on the label.
Python Program
import tkinter as tk
# Create the main window
window = tk.Tk()
# Create the menu bar
menu_bar = tk.Menu(window)
# Create the menu Menu1
menu_1 = tk.Menu(menu_bar, tearoff=0)
# Create a photo image
item_1_icon = tk.PhotoImage(file="gear-icon.png")
# Add items for Menu1
menu_1.add_command(label="Item1", image=item_1_icon, compound="left")
menu_1.add_cascade(label="Item2")
# Add the menu to the menu bar
menu_bar.add_cascade(label="Menu1", menu=menu_1)
# Attach the menu bar to the main window
window.config(menu=menu_bar)
# Start the Tkinter event loop
window.mainloop()
Output
Summary
In this Python Tkinter tutorial, we learned how to add an icon to the menu item in Tkinter, with the help of examples.