2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
有一個(gè)現(xiàn)有的 AutocompleteEntry 小部件。
例子:
from ttkwidgets.autocomplete import AutocompleteEntry
import tkinter as tk
window = tk.Tk()
Label1 = tk.Label(window, text="Entry:")
Label1.pack(side='left', padx=10, pady=10)
test_values = ['one', 'two', 'three']
test_var = tk.StringVar(window)
test_var.set('Default Value')
Entry1 = AutocompleteEntry(window, width=20, textvariable=test_var, completevalues=test_values)
Entry1.pack(side='left', padx=10, pady=10)
window.mainloop()

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
好的,在分析了這段代碼幾個(gè)小時(shí)后,我想出了如何使用該insert()方法將值設(shè)為默認(rèn)值。這樣做后我的第一個(gè)問題是列表框在應(yīng)用程序啟動(dòng)時(shí)默認(rèn)也是活動(dòng)的。通過向changed函數(shù)添加另一個(gè) if 條件,它不會(huì)打開列表框,直到值被清除。當(dāng)我添加條件語句時(shí),該行在self.lb.destroy()清除字段時(shí)會(huì)引發(fā)錯(cuò)誤:
AttributeError:“AutocompleteEntry”對(duì)象沒有屬性“l(fā)b”
我不確定為什么會(huì)拋出這個(gè)錯(cuò)誤,因?yàn)樗谖姨砑訔l件之前就起作用了。但是,lb未在類或函數(shù)的其他任何地方定義。刪除該行修復(fù)了錯(cuò)誤,一切似乎都按預(yù)期工作。這是我所做的更改。如果其他人有更好的解決方案,請(qǐng)告訴我。
class AutocompleteEntry(Entry):
# add settings argument which is True or False
def __init__(self, lista, settings, *args, **kwargs):
Entry.__init__(self, *args, **kwargs)
self.lista = lista
# define the self.settings object
self.settings = settings
self.var = self["textvariable"]
if self.var == '':
self.var = self["textvariable"] = StringVar()
self.var.trace('w', self.changed)
self.bind("<Return>", self.selection)
self.bind("<Up>", self.up)
self.bind("<Down>", self.down)
self.lb_up = False
def changed(self, name, index, mode):
if self.var.get() == '':
# self.lb.destroy() - removed this line
self.lb_up = False
# change this variable to False once the field is cleared
self.settings = False
# add if condition - field is not empty and settings is True
elif self.var.get() != '' and self.settings == True:
self.lb_up = False
else:
words = self.comparison()
if words:
if not self.lb_up:
self.lb = Listbox()
self.lb.bind("<Double-Button-1>", self.selection)
self.lb.bind("<Return>", self.selection)
self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
self.lb_up = True
self.lb.delete(0, END)
for w in words:
self.lb.insert(END,w)
else:
if self.lb_up:
self.lb.destroy()
self.lb_up = False
最后一部分:
if __name__ == '__main__':
root = Tk()
# define settings variable and add to AutoCompleteEntry arguments
settings = True
entry = AutocompleteEntry(lista, settings, root)
entry.insert(END, "this is the default value")
entry.grid(row=0, column=0)
Button(text='nothing').grid(row=1, column=0)
Button(text='nothing').grid(row=2, column=0)
Button(text='nothing').grid(row=3, column=0)
root.mainloop()
添加回答
舉報(bào)