Hit enter after type your search item

Python Tkinter Menu

Creating Menus in Python Applications by tkinter library

In this tutorial, we will show you how to create menus in the Python applications by tkitner library.

First, the examples will explain how to add a menu. Then we will add menu items as a user pulls/clicks on the menu.

Later, we will also show how to add sub menus inside the main menu.

Actions as you click on the menu item will also be covered in the examples below.

Syntax of creating a menu in tkinter

w = Menu(top, options)

An example of a menu with a single item

Let us start with a simple example of creating a main menu with a single item.

We will create “File” main menu and then it will contain one item “Open”.

As you open and click on the Open menu item, it closes the window.

Have a look at the code and output:



Adding more items to the menu example

Let us move ahead and add three items to the “File” menu:

  • New
  • Open
  • Save




Adding a separator between two menu items example

We will add a separator between each menu item (New, Open, and Save) for the demo only.

To add a separator, use the add_separator() method of the menu widget.

All items simply close the window as you click on any:




An example of multiple main menu

Now we will create more main menus like File in the above examples.

In the program below, we have

  • File
  • Edit
  • Format
  • View
  • Help

These are the main items. Upon clicking on any will open its own menu. But first only the main menus:




Adding menu items to each menu

In this example, we will add menu items for each main menu.

Python program:



An example of creating a sub-menu

If your menu is supposed to be multi-level i.e. sub-menu then you can do this easily by using tkinter menu widget.

For example, in our above menu, we want to add the “Zoom In” and “Zoom Out” sum menu items to the “Zoom” menu item. This is how we can do this:




Coloring the menu

The menu widget has options to give background and foreground colors to the menu.

  • By using bg option, you may specify the background color.
  • The fg option is used to color the text of the menu items.

See the example below where we added both options. In fg, we provided the color name and in the bg option we used the Hex value of the color:




Changing color as the mouse hovers over a menu item

To stand out a menu item from others when the mouse hovers over that item, use the following two options of the menu widget:

  • activebackground – to set the background color as mouse hovers
  • activeforeground – set the text color

See an example below where we set these options for all three menu items.




This div height required for enabling the sticky sidebar