问题
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