python - 使用 Python 创建具有级联功能的搜索栏
问题描述
我一直想知道是否可以使用 tkinter 中的条目小部件创建具有级联功能的搜索栏,或者是否有其他小部件可用于实现此目标,在我从事桌面应用程序开发期间,我只能要创建一个您必须输入要搜索的全名的查询,然后您将编写一个查询来获取条目并从数据库中获取您想要的任何信息,这对我来说非常重要,因为它限制了我,特别是当我想为商店创建应用程序时,那里有很多商品,您只需键入商品的第一个字母,它就会自动显示带有第一个字母的商品。如果有答案,我真的很感激......
解决方案
您需要做的就是绑定一个函数<Any-KeyRelease>
以在用户键入时过滤数据。调用绑定函数时,获取条目小部件的值,然后使用它来获取过滤后的值列表。
这是一个使用一组固定数据和一个列表框来显示数据的示例,但当然您也可以轻松地进行数据库查询并根据需要显示值。
import tkinter as tk
# A list of all tkinter widget class names
VALUES = [cls.__name__ for cls in tk.Widget.__subclasses__()]
class Example():
def __init__(self):
self.root = tk.Tk()
self.entry = tk.Entry(self.root)
self.listbox = tk.Listbox(self.root)
self.vsb = tk.Scrollbar(self.root, command=self.listbox.yview)
self.listbox.configure(yscrollcommand=self.vsb.set)
self.entry.pack(side="top", fill="x")
self.vsb.pack(side="right", fill="y")
self.listbox.pack(side="bottom", fill="both", expand=True)
self.entry.bind("<Any-KeyRelease>", self.filter)
self.filter()
def filter(self, event=None):
pattern = self.entry.get().lower()
self.listbox.delete(0, "end")
filtered = [value for value in VALUES if value.lower().startswith(pattern)]
self.listbox.insert("end", *filtered)
example = Example()
tk.mainloop()
推荐阅读
- c# - 将变量插入表中时出现语法错误 Visual Studios 2015 C#
- c# - Linq,排除 SQL Nulls
- kentico - 如何更改 Kentico 中的默认页面标题字段
- hibernate - Spring Data JPA 从多个表或视图中读取相同的实体
- sql - 可以创建连接到多个服务器的 SQL Server 存储过程吗?
- java - 删除一对多 grails 中的关联
- excel - Excel Vba索引匹配多个条件以返回精确匹配
- php - 在 PHP 中使用计数器确定结果
- r - 如何为 mxnet 安装 R 包?
- mysql - 特殊选择语句。根据其主要 SKU 选择所有 SKU