tkinter 自动完成小部件小写偏见 [英] tkinter autocomplete widget lowercase bias
问题描述
我在互联网上找到了一个有趣的自动完成小部件类——我已经将它精简到了基本要素——来制作我无聊的 python 2.7 tkinter 输入窗口自动完成输入窗口.
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')
我已经回到原来的互联网代码 http://tkinter.unpythonic.net/wiki/AutocompleteEntry 并显示相同的缺陷.如何更改自动完成小部件代码以消除这种偏差,使其接受包含大写和小写单词的列表?
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?
推荐答案
尝试删除
.lower()
来自
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.
这篇关于tkinter 自动完成小部件小写偏见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!