How to Create Menu Bar Using Tkinter in Python?

You are currently viewing How to Create Menu Bar Using Tkinter in Python?

The below is an example to show you how to create a menu bar using Tkinter in Python.

Python - Create Menu Bar Using Tkinter Example

In the following example, it will create a menu bar and will give the choices to the user to select. On selection, it will print on the screen and if the user will select the Quit option then it will exit the program.

import tkinter

def set_menu(window, choices):
    menubar = tkinter.Menu(root)
    window.config(menu=menubar)

    def _set_choices(menu, choices):
        for label, command in choices.items():
            if isinstance(command, dict):
                # Submenu
                submenu = tkinter.Menu(menu)
                menu.add_cascade(label=label, menu=submenu)
                _set_choices(submenu, command)
            elif label == '-' and command == '-':
                # Separator
                menu.add_separator()
            else:
                # Simple choice
                menu.add_command(label=label, command=command)

    _set_choices(menubar, choices)

if __name__ == '__main__':
    import sys

    root = tkinter.Tk()

    from collections import OrderedDict

    set_menu(root, {
        'File': OrderedDict([
            ('Open', lambda: print('Open!')),
            ('Save', lambda: print('Save')),
            ('-', '-'),
            ('Quit', lambda: sys.exit(0))
        ])
    })
    root.mainloop()

Output

Tkinter menu bar example.Open!

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.