我想知道这是否可能......?
想象一下带有输入框小部件的tkinter应用程序,用于输入PC名称。一旦用户开始在框中键入内容,应用程序将根据您键入的内容显示可能的名称,因此您输入的选项越多,您看到的选项就越少,只留下一个或足够小的选择在可用选项上。
如果在tkinter中可以做到这一点,如果有人能指出我的方向,那就太棒了!
我无法发布任何示例代码,因为这是一般而非具体的问题。
答案 0 :(得分:4)
您可以将StringVar
的实例与条目小部件相关联,然后在该实例上设置跟踪以在值更改时调用回调。然后,您可以在回调中执行任何操作 - 更新列表,弹出窗口等等。
以下是根据您输入内容简单过滤列表的示例。
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.choices = ("one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty")
self.entryVar = tk.StringVar()
self.entry = tk.Entry(self, textvariable=self.entryVar)
self.listbox = tk.Listbox(self)
self.listbox.insert("end", *self.choices)
self.entry.pack(side="top", fill="x")
self.listbox.pack(side="top", fill="both", expand=True)
self.entryVar.trace("w", self.show_choices)
self.listbox.bind("<<ListboxSelect>>", self.on_listbox_select)
def on_listbox_select(self, event):
"""Set the value based on the item that was clicked"""
index = self.listbox.curselection()[0]
data = self.listbox.get(index)
self.entryVar.set(data)
def show_choices(self, name1, name2, op):
"""Filter choices based on what was typed in the entry"""
pattern = self.entryVar.get()
choices = [x for x in self.choices if x.startswith(pattern)]
self.listbox.delete(0, "end")
self.listbox.insert("end", *choices)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()