Reputation: 161
I found a fun autocomplete widget class on the internet--which I've stripped down to the essentials--to make my boring python 2.7 tkinter entry windows autocomplete entry windows.
from Tkinter import*
class AutocompleteEntry(Entry):
def set_completion_list(self, completion_list):
self._completion_list = completion_list
self._hits = []
self._hit_index = 0
self.position = 0
self.bind('<KeyRelease>', self.handle_keyrelease)
def autocomplete(self, delta=0):
if delta:
self.delete(self.position,END)
else:
self.position = len(self.get())
_hits = []
for element in self._completion_list:
if element.startswith(self.get().lower()):
_hits.append(element)
if _hits != self._hits:
self._hit_index = 0
self._hits=_hits
if _hits == self._hits and self._hits:
self._hit_index = (self._hit_index + delta) % len(self._hits)
if self._hits:
self.delete(0,END)
self.insert(0,self._hits[self._hit_index])
self.select_range(self.position,END)
def handle_keyrelease(self, event):
if len(event.keysym)== 1:
self.autocomplete()
class Code:
def __init__(self, parent):
self.myParent = parent
self.main_frame = Frame(parent, background="light blue")
self.main_frame.pack(expand=YES, fill=BOTH)
test_list = ('test', 'type', 'true', 'tree')
self.enter = AutocompleteEntry(self.main_frame, width=30)
self.enter.set_completion_list(test_list)
self.enter.pack(side=LEFT, expand=NO)
root = Tk()
code = Code(root)
root.mainloop()
Works great, with one annoying caveat: seems the list which the autocomplete references is bias towards lowercase words. This snippet works:
test_list = ('test', 'type', 'true', 'tree')
Change the list to uppercase and the autocomplete function vanishes.
test_list = ('Test', 'Type', 'True', 'Tree')
I've gone back to the original internet code http://tkinter.unpythonic.net/wiki/AutocompleteEntry and it shows the same flaw. How do I alter the autocomplete widget code to eliminate this bias, allowing it to accept lists with upper and lowercase words?
Upvotes: 2
Views: 1486
Reputation: 8767
Try removing the
.lower()
from
if element.startswith(self.get().lower()):
or to make the match case-insensitive:
if element.lower().startswith(self.get().lower()):
which will convert your entry string into lowercase and then the list values to lowercase as well so that a match will be made anytime the same letters are entered even if the case is off.
Upvotes: 4