在输入框中输入内容后,自动显示符合输入内容的选项,选择后自动填充到输入框中。
"""一个搜索提示框"""
import tkinter as tk
from tkinter import Listbox, ttk
class MyUi(tk.Tk):
def __init__(self):
super().__init__()
self.title('搜索提示框示例')
self.geometry("480x320+400+200")
ttk.Style().configure('.', font=("仿宋", 15))
self.myentry_text = ''
self.mainUi()
self.mainloop()
def mainUi(self):
ttk.Label(self,text='这里输入').grid(padx=15,pady=5,row=0,column=0)
self.myentry = ttk.Entry(self)
self.myentry.grid(padx=5,pady=5,row=0,column=1)
self.myentry.configure(font=("仿宋", 13))
self.myentry.configure(validate="focusin")
self.myentry.configure(validatecommand=self.research)
# self.myentry.insert(0,'你')
def research(self):
"""搜索并显示在列表框内"""
research_content = ['csdn','csdn你好','csdn你在哪里?','一个学习编程的好网站','编程爱好者的网站']
current_input = self.myentry.get()
if current_input != self.myentry_text:
self.myentry_text = current_input
Listbox_content = []
for _c in research_content:
if current_input in _c:
Listbox_content.append(_c)
# 添加listbox控件
mylistbox = tk.Listbox(self)
mylistbox.grid(padx=5,pady=5,row=1,column=1)
mylistbox.bind("<<ListboxSelect>>", self.show)
# 清空内容
mylistbox.delete(0,tk.END)
# 插入内容
for content in Listbox_content:
mylistbox.insert(tk.END, content)
self.id = self.after(2000, self.research)
def show(self, event):
"""根据选择的内容,填充到输入框。然后销毁listbox"""
# 取得事件对象object
object = event.widget
# 取得所选的项目索引
index = object.curselection()
# 由索引取得所选的项目,填充到输入框中
self.myentry.delete(0,tk.END)
self.myentry.insert(0,object.get(index))
self.after_cancel(self.id)
# 然后销毁listbox
object.grid_forget()
# 退出循环
self.after_cancel(self.id)
if __name__ == "__main__":
MyUi()
不足之处,请大佬指正!
|