首页 > 解决方案 > 使用 Python 创建具有级联功能的搜索栏

问题描述

我一直想知道是否可以使用 tkinter 中的条目小部件创建具有级联功能的搜索栏,或者是否有其他小部件可用于实现此目标,在我从事桌面应用程序开发期间,我只能要创建一个您必须输入要搜索的全名的查询,然后您将编写一个查询来获取条目并从数据库中获取您想要的任何信息,这对我来说非常重要,因为它限制了我,特别是当我想为商店创建应用程序时,那里有很多商品,您只需键入商品的第一个字母,它就会自动显示带有第一个字母的商品。如果有答案,我真的很感激......

标签: pythontkinteruisearchbar

解决方案


您需要做的就是绑定一个函数<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()

推荐阅读