如何解决 StringVar.get() 问题

How to fix StringVar.get() issue

我正在尝试使用 StringVar 在 Tkinter 中制作自动完成 GUI(如 Google)。我定义了一个回调函数,我在其中使用了 StringVar.get(),我在 Entry 中针对不同的输入通过 ListBox 中的自动完成建议获得了不同的输出。问题是,在 Entry 中输入一个字母后,我得到正确的输出,但在输入 2 个或更多字母后,我得到空的 ListBox。这是代码。

num=input()
num=int(num)
sv=StringVar()
def callback(sv,list,num):
    a=sv.get()
    pom_list = list
    bin_list = []
    lexicographic_sort(pom_list)
    x = binary_search(a, pom_list)
    while x != -1:
        bin_list.append(x)
        pom_list.remove(x)
        x = binary_search(a, pom_list)

    i = 0
    l = Listbox(root, width=70)
    l.grid(row=2, column=5)
    if len(bin_list) == 0 or len(a) == 0:
        l.delete(0, END)

    else:
        for list1 in bin_list:
            if i == num:
                break
            l.insert(END, list1[0])
            i += 1
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv,list,num))
te = Entry(root, textvariable=sv)
te.grid(row=1,column=5)

其中 list outside callback function 是所有建议的列表,bin_list 是使用 binary_search.[=14 的 StringVar.get() 的建议列表=]

这是因为第一个字母的所有匹配项都已从搜索列表中删除。您应该在 callback() 中使用克隆的搜索列表。也不要创建新列表来显示结果列表,创建一次结果列表并在 callback() 中更新其内容。 此外,预先对搜索列表进行排序:

def callback(sv, wordlist, num):
    result.delete(0, END) # remove previous result
    a = sv.get().strip()
    if a:
        pom_list = wordlist[:]  # copy of search list
        #lexicographic_sort(pom_list)  # should sort the list beforehand
        x = binary_search(a, pom_list)
        while x != -1 and num > 0:
            result.insert(END, x)
            pom_list.remove(x)
            num -= 1
            x = binary_search(a, pom_list)

...

lexicographic_sort(wordlist)
sv = StringVar()
sv.trace("w", lambda *args, sv=sv: callback(sv, wordlist, num))

...

result = Listbox(root, width=70)
result.grid(row=2, column=5)