Tkinter - Window Menu in Python

Tkinter also allows the gui to contain a menu. Here is simple example of this:

#import Tkinter
import tkinter

#example function to execute on selection
def functionExample():
    print ("Menu Item Selected")

#create a window
window = tkinter.Tk()

#Sets window title
window.title("Menu Example")

#Create a Label
lbl1 = tkinter.Label(window, text="   Try the menu   ")
lbl1.pack()

#defines a menu item
menuname = tkinter.Menu(window)

#creates a menu group
menu_1 = tkinter.Menu(menuname, tearoff=0)

#Creates a menu item, with command
menu_1.add_command(label="Option 1", command = functionExample)
menu_1.add_command(label="Option 2", command = functionExample)
menu_1.add_command(label="Option 3", command = functionExample)
menu_1.add_command(label="Option 4", command = functionExample)
menu_1.add_command(label="Option 5", command = functionExample)
#Adds menu_1 to the menu bar with the heading Group 1
menuname.add_cascade(label="Group1", menu=menu_1)

menu_2 = tkinter.Menu(menuname, tearoff=0)
menu_2.add_command(label="Option 1", command = functionExample)
menu_2.add_command(label="Option 2", command = functionExample)
menu_2.add_command(label="Option 3", command = functionExample)
menu_2.add_command(label="Option 4", command = functionExample)
#Creates a line separator between items
menu_2.add_separator()
menu_2.add_command(label="Option 5", command = functionExample)
menuname.add_cascade(label="Group2", menu=menu_2)

menu_3 = tkinter.Menu(menuname, tearoff=0)
menu_3.add_command(label="Option 1", command = functionExample)
menu_3.add_separator()
menu_3.add_command(label="Option 2", command = functionExample)
menuname.add_cascade(label="Group3", menu=menu_3)

#add the menu to the window
window.config(menu=menuname)

#Loops the tkinter window
window.mainloop()

This creates this frame:

With the following menu:

When an item is selected it runs the set command function.
Menu Item Selected





Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Must Read Articles

Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter _ Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines and labels.
Tkinter - Pack vs Grid vs Place - tkinter provides flexibility in how the layout the widgets. 
Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.