Tkinter Menu Alt shortcut
The shortcut is to add an underline to a single letter within the English string of a menu category or list command, then you can use the Alt key to start the function first, and when the menu displays the underline letter, you can start the function directly by pressing the specified letter key. The design approach is to add the underline parameter to the following two methods.
add_cascade(..., underline=n) # n represents the first index letter with an underscore
add_command(..., underline=n) # n represents the first index letter with an underscore
The underline of add_cascade( ) adds a letter underline to the menu category, and the underline of add_command( ) adds a letter underline to the command list, with the above indexes counting from 0. Of course, when processing the selected letters with underlines, you must moderately select representative letters, which will usually be the first letter of the string. For example, the File menu may select F, the Help menu may select H, and so on. Sometimes it happens that the first letter of the string is repeated with the previous letter, for example, the S of Save with the S of Save As, in which case the second occurrence of the string can be appropriately selected with other letters, as can be seen in the following example.
Example#1
Create shortcuts for menu categories and list commands.
from tkinter import *
from tkinter import messagebox
def newFile():
messagebox.showinfo("New File","New File")
def openFile():
messagebox.showinfo("Open File","Open File")
def saveFile():
messagebox.showinfo("Save File","Save File")
def saveAsFile():
messagebox.showinfo("SaveAs File","SaveAs File")
def aboutMe():
messagebox.showinfo("About Me","About Me")
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
menubar = Menu(root) # Create top-level menu
# Create a menu category object, and name this menu category as File
filemenu = Menu(menubar)
menubar.add_cascade(label="File",menu=filemenu,underline=0)
# Create a menu list within the File menu
filemenu.add_command(label="New File",command=newFile,underline=0)
filemenu.add_command(label="Open File",command=openFile,underline=0)
filemenu.add_separator()
filemenu.add_command(label="Save File",command=saveFile,underline=0)
filemenu.add_command(label="Save As File",command=saveAsFile,underline=5)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy,underline=0)
# Create a menu category object, and name this menu category Help
helpmenu = Menu(menubar)
menubar.add_cascade(label="Help",menu=helpmenu,underline=0)
# Create a menu list within the Help menu
helpmenu.add_command(label="About Me",command=aboutMe,underline=1)
root.config(menu=menubar) # Show menu objects
root.mainloop()
Output:
You can see that the F of File and the H of Help contain the underline, press F to open the File menu, click Alt+F
to display the following.