tkinter制作一个搜索提示框
时间: 2023-12-03 13:27:11 浏览: 137
好的,以下是一个简单的示例代码,可以实现一个搜索提示框:
```python
import tkinter as tk
class AutocompleteEntry(tk.Entry):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.var = self["textvariable"]
if self.var is None:
self.var = self["textvariable"] = tk.StringVar()
self.var.trace('w', self.update_list)
self.listbox = tk.Listbox()
def update_list(self, *args):
search_term = self.var.get()
if len(search_term) > 0:
self.listbox.delete(0, tk.END)
results = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
for item in results:
if search_term.lower() in item.lower():
self.listbox.insert(tk.END, item)
self.listbox.place(x=self.winfo_x(), y=self.winfo_y() + self.winfo_height())
else:
self.listbox.delete(0, tk.END)
self.listbox.place_forget()
def handle_selection(self, event):
self.var.set(self.listbox.get(tk.ACTIVE))
self.listbox.delete(0, tk.END)
self.listbox.place_forget()
self.focus_set()
root = tk.Tk()
label = tk.Label(root, text="Enter a search term:")
label.pack()
entry = AutocompleteEntry(root)
entry.pack()
entry.bind('<Return>', lambda e: print(entry.get()))
entry.listbox.bind('<Double-Button-1>', entry.handle_selection)
entry.listbox.bind('<Return>', entry.handle_selection)
entry.listbox.bind('<Escape>', lambda e: entry.listbox.place_forget())
root.mainloop()
```
这个搜索提示框使用了一个 `AutocompleteEntry` 类来继承自 `tk.Entry`,并在其上添加了一个下拉列表框。当用户输入搜索词时,下拉列表框会显示所有包含该词的结果。用户可以通过鼠标或键盘选择一个结果,或者按下 `Enter` 键来选择当前高亮的结果。如果用户按下 `Escape` 键,下拉列表框会消失。
阅读全文