One of the most common elements in the GUI is the menu bar. A menu bar is normally under the title bar to display the series of menus. After clicking one of the top-level menus, a sub-menu will be extended to display more relevant menu items. A sub-menu is normally bound to the specific command like
Tkinter Basic Menubar
We will create our first menubar example that has
File menu as in most editors. We only include
Quit sub-menus for simplicity.
menubar = tk.Menu(app)
The given parameter of the
Menu is the parent widget of the created menu. The code line above means that the menu widget
menubar will be the top level of the frame
filemenu = tk.Menu(menubar)
filemenu is the menu of the widget
menubar, or sub menu of the frame
add_command adds the commands to the menu
label is the text displayed in the sub menu.
filemenu is added to
menubar with the command
File is the menu label displayed in the top level of the frame
menubar is created to be child widget of
app as we explained above, you still need to config it to be the
app. Otherwise, no menu bar will be shown in the GUI.
It doesn’t respond at all if you click the options like
Save in the sub menu of
File because there is no command attached to them yet. We will make the command functional in the next session.
Tkinter Menubar Command
filemenu = tk.Menu(menubar, tearoff=0)
tearoff is set to be
1 by default and it would detach menus from the main window to create a floating menu if the dotted lines at the top is clicked. Here it is set to be
0 to disable this floating feature.
onOpen function is bound to the menu
Open, and will be called when
Open is clicked.
def onOpen(): print(filedialog.askopenfilename(initialdir = "/",title = "Open file",filetypes = (("Python files","*.py;*.pyw"),("All files","*.*"))))
This function displays the open dialog and returns the selected filename. We don’t really open the file in our example but to print its filename.
tkfiledialog has three functions,
||Directory, Title, Extension||To open file: Dialog that requests selection of an existing file.|
||Directory, Title, Extension||To save file: Dialog that requests creation or replacement of a file.|
||None||To open directory|
Tkinter has an internal
quit function that quits the root GUI. We could simply bind this existing function to
Exit rather than creating our own