How to fix StringVar.get() issue

我的梦境 提交于 2020-05-09 07:04:10

问题


I am trying to make autocomplete GUI (like Google's) in Tkinter using StringVar. I defined a callback function , where i used StringVar.get(), where I for different input in Entry I get different output via autocomplete suggestions in ListBox. The problem is that after typing one letter in Entry I get right output but after typing 2 or more I get empty ListBox. Here's the code.

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)

where list outside callback function is a list of all suggestions, and bin_list is a list of suggestions of StringVar.get() using binary_search.


回答1:


It is because all matched items for the first letter have been removed from the search list. You should use a cloned search list in callback(). Also don't create new list to show the result list, create the result list once and update its content in callback(). Furthermore, sort the search list beforehand:

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)


来源:https://stackoverflow.com/questions/61334505/how-to-fix-stringvar-get-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!