Tkinter Menu Ctrl+Shortcuts
In the design of the menu list can also be designed on the right side of the command Ctrl + X and other shortcuts, X is the English letter representing a shortcut key, to design this type of operation can be used with the aid of accelerator parameters, and then use the bind ( ) method to bind this shortcut key to a callback ( ) method. In order to make the program simple, you can use the Ctrl+shortcut method.
Example#1
To design the New File submenu of the File menu, you can press the Ctrl+N key combination.
from tkinter import *
from tkinter import messagebox
def newFile():
messagebox.showinfo("New File","New File")
def controlN(event):
messagebox.showinfo("New File","New File-CONTROL+N")
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,accelerator="Ctrl+N")
# After experimenting with #,accelerator="Ctrl+N") this part of the previous line of code can be deleted directly without visible effects
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy,underline=0)
root.config(menu=menubar) # Show menu objects
root.bind("<Control-N>",lambda event:messagebox.showinfo("New File","New File-lambda"))
# root.bind("<Control-N>",controlN)
# Note: <Control-N> is case-sensitive for shortcut keys. Use uppercase N when pressing a key.
root.mainloop()
In the main screen, directly type CTRL+N
,output:
In the above lines 18 and 19 is the implementation of the Ctrl + N shortcut key binding, because the bound event will return event events to the callback ( ) method, so you can not directly call the newFile ( ) method in lines 3 and 4, because the newFile ( ) method does not pass any parameters, if you run into this problem by intuition and then create a method dedicated to the use of this shortcut key, this example uses Lambda expressions to handle to simplify the design of the entire program.