Weare going to see how to add a menu to a window with tkinter.
The window
A window will be like this:
import tkinter as tk root = tk.Tk() root.mainloop()
A text widget
Let’s add a text widget to the window (it is not necessary to make a menu, but we just want to populate the window with just one widget.
import tkinter as tk root = tk.Tk() text = tk.Text(root) text.pack() root.mainloop()
The menu bar
menu = tk.Menu(root)
We create a single voice of the menu
menu = tk.Menu(root) #Add just a voice, with no sub voices menu.add_command(label="Open")
To add a ‘cascade voice’ to the menu we do this: we create another menu, with another name, we use add_command to create a voice for this menu:
# add a cascade menu submenu = tk.Menu(root) submenu.add_command(label="Save file")
And then we use add_cascade to make this menu a menu ‘cascade’ in which a new submenu is shown when you press the label that you will see in the next line:
menu.add_cascade(label="File", menu=submenu)
You still can’t see the menu. To see it, you got to do this:
root.config(menu=menu)
The whole code
import tkinter as tk root = tk.Tk() text = tk.Text(root) text.pack() menu = tk.Menu(root) #Add just a voice, with no sub voices menu.add_command(label="Open") # add a cascade menu submenu = tk.Menu(root) submenu.add_command(label="Save file") menu.add_cascade(label="File", menu=submenu) root.config(menu=menu) root.mainloop()
Tkinter test for students
Tkinter articles
