Python Tkinter: Have Entry receive keys while Menu is posted?

China☆狼群 提交于 2020-01-17 03:45:11

问题


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()

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.

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/34815500/python-tkinter-have-entry-receive-keys-while-menu-is-posted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!