Tk Listbox bindings

Stephen J. Turner sjturner at ix.netcom.com
Fri Dec 10 10:23:58 EST 1999


Hans Nowak wrote:
> While it's easy to bind mouse events to a listbox, I haven't managed
> to bind keyboard events to it. In a current project I have a listbox
> and I want my users to be able to scroll through it using common keys
> like <Up> and <Down>. However, binding them to the listbox, as done
> above, does not work; I don't know why.
> 
> If I do a bind_all, it does work, though. Unfortunately, this is not
> the right way to do it; I have another window with a ScrolledText
> widget, and if I scroll there, the listbox scrolls too, due to the
> bind_all effect!
> 
> Experimenting, I also tried binding "<Down>" (etc) to all widgets in
> the current frame, which doesn't work either.
> 
> So my obvious question is, how can I bind keyboard events to a
> listbox without having to use bind_all?

The problem is that key press/release events are sent to the widget that
currently has input focus, which by default is the toplevel window.  To
explicitly set focus to the listbox when clicked, use something like the
following:

class display_list(Frame):
    def __init__(self, parent, items, height = 15, width = 20):
        # ... initialization snipped ...
        self.listbox.bind('<ButtonRelease-1>', self.setfocus)

    def setfocus(self, ev):
        self.listbox.focus()

Incidentally, the <Up> and <Down> behavior you described is already in
Tk's default listbox bindings (see listbox.tcl), so you should be done
once you set focus.

Regards,
Stephen

--
Stephen J. Turner <sjturner at ix.netcom.com>



More information about the Python-list mailing list