Python Tkinter:在发布菜单时是否有条目接收键? [英] Python Tkinter: Have Entry receive keys while Menu is posted?

查看:23
本文介绍了Python Tkinter:在发布菜单时是否有条目接收键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有下拉菜单自动完成功能的条目......有点像 Chrome 的 omnibar,例如.

I want to have an Entry with a dropdown Menu autocomplete... kind of like Chrome's omnibar, for example.

我遇到的一个问题是,一旦菜单被发布(显示),它似乎会拦截所有按键事件,而且我没有看到将它们重定向到其他任何地方的方法.

One issue I'm having is that once the menu gets posted (displayed), it seems to intercept all key press events, and I don't see a way to redirect them anywhere else.

以下是重现问题的一些简化代码:

Here's some simplified code that reproduces the issue:

from Tkinter import Entry, Menu, Tk

def menuKey(event):
    print('Key pressed in a menu.')

def showMenu(event):
    menu = Menu(root, tearoff = 0)
    menu.add_command(label = 'Just for example')
    menu.bind('<KeyRelease>', menuKey)
    menu.post(entry.winfo_rootx(), entry.winfo_rooty() + entry.winfo_height())

root  = Tk()
entry = Entry(root, width = 50)
entry.bind('<KeyRelease>', showMenu)
entry.bind('<FocusIn>', showMenu)
entry.pack()
root.mainloop()

单击条目后,它会显示菜单.尝试打字.在 Windows 上,您只会听到错误提示音.在 OS X 上,它会突出显示菜单中的某些内容.两个操作系统都不做我真正想要的,即运行 menuKey 函数.

It shows the menu once you click on the entry. Try typing. On Windows, you just get an error beep sound. On OS X, it highlights something in the menu. Neither OS does what I actually want, which is to have the menuKey function run.

有什么方法可以拦截进入 Menu 的关键事件和/或强制它们进入 Entry 吗?

Is there some way I can either intercept key events that are going to the Menu and/or force them to go to the Entry instead?

推荐答案

您说得对:本机菜单会窃取所有事件,而您对此无能为力.这是我们为在 OSX 和 Windows 上拥有本机菜单而付出的代价.

You are correct: the native menus steal all of the events, and there's nothing you can do about it. This is the price we pay for having native menus on OSX and Windows.

解决方法是不使用下拉菜单.相反,您可以创建 Toplevel 的实例,打开 overrideredirect 标志,然后自己管理所有事件.这有点麻烦,但它是可行的.

The workaround is to not use a menu for the dropdown. Instead, you can create an instance of Toplevel, turn on the overrideredirect flag, and then manage all of the events yourself. It's a bit of a chore, but it's doable.

这篇关于Python Tkinter:在发布菜单时是否有条目接收键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆