Python 3 中 tkinter 的键盘快捷键

Keyboard shortcuts with tkinter in Python 3

我在 Python 3 中创建了一个菜单栏,我想知道如何向其添加键盘快捷键和加速器。比如点击 "F" 进入文件菜单等等。

通过一些挖掘我找到了 "underline=" 属性,但它似乎在 Python 中不起作用 3. 当我尝试它时它不起作用,唯一的文档我发现它适用于 Python.

的早期版本
    menubar = Menu(master)

    filemenu = Menu(menubar, tearoff=0)
    .....
    menubar.add_cascade(label="File", underline=0, menu=filemenu)

在 Python 3 中有没有办法用 tkinter 做这些事情?

考虑阅读 (http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm)

您必须将小部件绑定到函数的事件:

Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget:

正在捕获键盘事件

from Tkinter import *

root = Tk()

def key(event):
    print "pressed", repr(event.char)

def callback(event):
    frame.focus_set()
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

If you run this script, you’ll find that you have to click in the frame before it starts receiving any keyboard events.

不久前,我按照本指南实现了对我的一个函数的 ctrl+f 绑定:

toolmenu.add_command(label="Search Ctrl+f", command=self.cntrlf)
root.bind('<Control-f>', self.searchbox)
def cntrlf(self, event):
    self.searchbox()

对于您的文件菜单,您可能需要考虑实施加速器:

menubar.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Exit", command=quit, accelerator="Ctrl+Q")
config(menu=menubar) 

对于菜单选项,请记住使用 ALT 后跟选项名称的第一个字母

file 菜单 = ALT 后跟 f 工具菜单 = ALT 后跟 t 等等

希望这对您有用

is there a way for the frame to receive events without clicking on the frame? If i scrolled over to the frame to click on it, i have already used time to get over there, might as well just click on the button as opposed to use the shortcut key.

答案是将整个 root/master/window 绑定到一个键绑定,这样每当您按下该键时,就会调用一个函数来完成您的任务。

import sys
from tkinter import *
root=Tk()
Menu_bar = Menu(root)
m1 = Menu(Menu_bar, tearoff=0)
m1.add_command(label="exit", command=sys.quit)
Menu_bar.add_cascade(label="file", menu=m1)

root.bind("<Alt_L><f>", sys.quit)
root.mainloop

应该这样做