Question: How to Prevent Tkinter Menu from Taking Keyboard Focus

galyle galyle at gmail.com
Mon Oct 3 15:55:37 EDT 2011


Hello, I'm trying to build a menu which provides suggestions to a user
based on input to an entry.  I have done something like this before
using Tcl/Tk, so I expected that it would work without much difficulty
with Tkinter.  I was wrong.

The problem I have is that, as soon as the menu is posted, it appears
to take the keyboard focus until the user either selects an option or
clicks an area outside of the menu.  The behavior I would like is for
keyboard input to go to the entry, and for the menu to update based on
that input.  I have tried different bindings (both to the entry and
menu) and I have tried different focus/grab combinations (even
force_focus and grab_set_global to the entry) when the menu is posted,
but nothing seems to work.  Are there any suggestions on how to get
the behavior I'm seeking?  The following code demonstrates the issue
I'm having:


import Tkinter

class demo:
    def __init__(self, parent):
        self._entry = Tkinter.Entry(width = 60)
        self._suggestions = Tkinter.Menu(parent, tearoff = 0,
takefocus = 0)
        self._entry.pack(padx = 20, pady = 20)
        self._entry.bind('<Key>', self._suggest_text, add = '+')

    def _suggest_text(self, event):
        curr = self._entry.get() + repr(event.char)[1]
        x = self._entry.winfo_rootx()
        y = self._entry.winfo_rooty()
        y += self._entry.winfo_height()
        try:
            self._suggestions.delete(0, 'end')
            self._suggestions.add_command(label = curr + '_1')
            self._suggestions.add_command(label = curr + '_2')
            self._suggestions.add_command(label = curr + '_3')
            self._suggestions.add_command(label = curr + '_4')
            self._suggestions.post(x, y)
        finally:
            self._suggestions.grab_release()

if __name__ == '__main__':
    root = Tkinter.Tk()
    root.title('A Problem')
    demo(root)
    root.mainloop()



More information about the Python-list mailing list