Keyboard-aware Tkinter listbox?
Martin Franklin
mfranklin1 at gatwick.westerngeco.slb.com
Wed May 15 12:01:36 EDT 2002
On Wednesday 15 May 2002 2:07 pm, Stephen Ferg wrote:
> I've been using the Tkinter LISTBOX, but it seems to have some
> limitations. Other LISTBOX implementations that I'm familiar with
> automatically sort the list of entries and support keyboard selection.
> By keyboard selection, I mean that if you had a list like this:
> So... I thought that before I try to build this myself, I'd like to
> ask if anyone knows if this has already been done?
>
Steve,
Tkinter does not have this functionallity but it would not be too hard to
roll your own, basically bind <Any-Key> to a function that searches through
you list box contents (a sorted list object will do) when it finds on that
matches call the selection_set and see methods on the Listbox add a pinch of
salt and your done!
somthing like.....(barely tested!)
import string
import Tkinter
class AutoListbox(Tkinter.Frame):
def __init__(self, parent, list_data=[]):
Tkinter.Frame.__init__(self, parent)
self.listbox=Tkinter.Listbox(self)
self.listbox.pack()
self.list_data=list_data
self.list_data.sort()
self.setlist()
parent.bind('<Any-Key>', self.bound)
def setlist(self):
self.listbox.delete(0, 'end')
for thing in self.list_data:
self.listbox.insert('end', thing)
def bound(self, event):
key=event.keysym
if len(key)<=1:
if key in string.letters:
## print key # now find it in list.....
## before we clear get the selected
try:
start_n=int(self.listbox.curselection()[0])
except IndexError:
start_n=-1
## clear the selection.
self.listbox.selection_clear(0, 'end')
## start from previous selection +1
for n in range(start_n+1, len(self.list_data)):
item=self.list_data[n]
if item[0].lower()==key.lower():
self.listbox.selection_set(first=n)
return
else:
# has not found it so loop from top
for n in range(len(self.list_data)):
item=self.list_data[n]
if item[0].lower()==key.lower():
self.listbox.selection_set(first=n)
## should call see method but don't have
## scrollbars in this demo!
return
if __name__=='__main__':
root=Tkinter.Tk()
alb=AutoListbox(root, list_data=['abc', 'bcd', 'bcde', 'cdefg'])
alb.pack()
root.mainloop()
HTH
Martin
More information about the Python-list
mailing list