Current location - Recipe Complete Network - Complete cookbook of home-style dishes - How to add shortcut keys similar to the options in the menu in python tkinter?
How to add shortcut keys similar to the options in the menu in python tkinter?
Tkinter in python needs to use an accelerator to add shortcut keys to the menu. Only this option is displayed, and the function of the accelerator key is not realized. Adding a function requires key binding, and the code is as follows:

From where? tkinter? Import? *

Root? =? Tk()

def? Callback ():

Print ("~ Call ~")

#? Create a top-level menu

Menu bar? =? Menu (root)

#? Create a drop-down menu file and add it to the top-level menu.

File menu? =? Menu (menu bar, tearoff=False)

file menu . add _ command(label = " open ",? Command = callback, Accelerator ='Ctrl+N')

file menu . add _ command(label = " save ",? Command = callback)

filemenu.add_separator()

file menu . add _ command(label = " exit ",? command=root.quit)

menubar . add _ cascade(label = " file ",? Menu = File menu)

#? Show menu

root.config(menu=menubar)

root . bind _ all(" & lt; Control-n >,? λ? Event:? Print ('shortcut Ctrl+N'))

Mainloop () has the following effects:

Remarks: Accelerator

1. Displays the shortcut key (shortcut key) for this menu item.

2. For example, accelerator = "Ctrl+N "

3. Only this option is displayed, and the key acceleration function is not realized (through key binding).