Skip to main content

A reusable Tkinter search widget with fuzzy multi-word matching

Project description

tksearchengine

tksearchengine provides a reusable Tkinter search field with fuzzy, multi-word suggestions. It combines an entry, a search button, and a listbox in a single configurable widget.

Features

  • Placeholder text while the empty entry is not focused.
  • Live suggestions while the entry is focused.
  • Mouse selection and keyboard navigation with Up and Down.
  • Tab accepts the highlighted suggestion, or the first suggestion by default.
  • Return and the search button invoke the same callback.
  • Case-insensitive, accent-insensitive, multi-word fuzzy matching.
  • - and ' are treated as word separators.
  • Missing spaces and spaces accidentally replaced by n or b are handled.
  • Exact words, exact prefixes, approximate prefixes, and approximate complete words are ranked in that order.
  • No third-party runtime dependencies.

Requirements

  • Python 3.10 or newer.
  • Tkinter, which is included with many Python installations but may require a separate operating-system package on Linux. For example, Debian and Ubuntu provide it in the python3-tk package.

Installation

From PyPI:

python -m pip install tksearchengine

From the project directory:

python -m pip install .

For editable development:

python -m pip install -e .

Basic usage

import tkinter as tk

from tksearchengine import SearchEngine


def run_search(text: str, selected_item: str | None) -> None:
    print("Search text:", text)
    print("Selected suggestion:", selected_item)


root = tk.Tk()

search = SearchEngine(
    root,
    items=["Paris", "Marseille", "Lyon", "Orléans"],
    command=run_search,
    placeholder="Search for a city",
    max_visible_results=6,
)
search.pack(fill="x", padx=20, pady=20)

root.mainloop()

Configuration

The constructor accepts:

  • items: searchable strings.
  • command: callback receiving the current text and the selected suggestion. The second argument is None when the user submits free text without accepting a suggestion.
  • placeholder: text displayed when the unfocused entry is empty.
  • button_text: label or symbol displayed on the search button.
  • search_function: optional replacement for the complete ranking function.
  • max_distance_function: optional function returning the accepted edit distance for a given reference-word length.
  • max_visible_results: maximum visible listbox rows.
  • placeholder_color and text_color: entry text colors.
  • entry_options, button_options, and listbox_options: mappings forwarded to the corresponding Tkinter widgets.
  • Any remaining keyword arguments are forwarded to the containing tk.Frame.

Here is the __init__ shape:

    def __init__(
        self,
        master: tk.Misc | None = None,
        *,
        items: Sequence[str] = (),
        command: SearchCallback | None = None,
        placeholder: str = "Search…",
        button_text: str = "🔍",
        search_function: SearchFunction | None = None,
        max_distance_function: MaxDistanceFunction = _default_max_distance,
        max_visible_results: int = 8,
        placeholder_color: str = "grey",
        text_color: str = "black",
        entry_options: Mapping[str, Any] | None = None,
        button_options: Mapping[str, Any] | None = None,
        listbox_options: Mapping[str, Any] | None = None,
        **frame_options: Any,
    ) -> None:

Example with widget customization:

search = SearchEngine(
    root,
    items=["Paris", "Marseille", "Lyon", "Orléans"],
    entry_options={
        "width": 32,
        "font": ("Segoe UI", 11),
        "relief": "solid",
    },
    button_options={
        "text": "Search",
        "font": ("Segoe UI", 10, "bold"),
        "padx": 12,
    },
    listbox_options={
        "font": ("Segoe UI", 10),
        "height": 6,
        "activestyle": "dotbox",
    },
)

These mappings are passed directly to tk.Entry, tk.Button, and tk.Listbox. SearchEngine still owns the entry text variable, the button command, the listbox selection behavior, and the visible result count.

A custom search function has this shape:

from collections.abc import Sequence


def custom_search(items: Sequence[str], query: str) -> Sequence[str]:
    normalized_query = query.lower()
    return [item for item in items if normalized_query in item.lower()]

Pass it with search_function=custom_search. When a custom search function is provided, it is responsible for filtering and ordering all results.

Public methods

  • get() returns the current search text without the placeholder.
  • set(text) replaces the current search text.
  • set_items(items) replaces the searchable collection.
  • invoke() runs the configured callback.
  • selected_item returns the highlighted or accepted suggestion, if any.

Matching behavior

The default matcher normalizes text to lowercase, replaces common accented letters with their unaccented forms, and treats - and ' as spaces. Results are ranked by:

  1. number of unmatched query words;
  2. match type, from exact word to approximate complete word;
  3. normalized Levenshtein distance;
  4. query-word order;
  5. original item order.

The default maximum edit distance is (word_length + 2) // 5. Override max_distance_function(word_length) when an application needs stricter or more permissive matching.

Running the example

The example contains 1,000 French commune names:

python examples/communes.py

Filtering the 1,000 sample names should feel immediate on a typical desktop Python installation.

Running the tests

After an editable installation:

python -m unittest discover -s tests -v

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tksearchengine-1.0.0.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tksearchengine-1.0.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file tksearchengine-1.0.0.tar.gz.

File metadata

  • Download URL: tksearchengine-1.0.0.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for tksearchengine-1.0.0.tar.gz
Algorithm Hash digest
SHA256 77db7ca2c52ba1458376329aceed97bb382fb93c284c67022902a11b55fc3251
MD5 7036fa20dd0dc7bc36608e67e155feaf
BLAKE2b-256 4b3e51a7ef9dc4e96452576177314b66b9a35d7ec6a353a9a61a4c9ee7784f1c

See more details on using hashes here.

File details

Details for the file tksearchengine-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: tksearchengine-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for tksearchengine-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6507355a1b19b99196ba35f423a71c554cc271ac8984d760763e4229bdbd344e
MD5 2d1493e2ba937b9b1a7c75cc9af99423
BLAKE2b-256 2b9b965f262b66a8706d82f370f2878545cd67a17dc80541bf5fd2e98aa1d62e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page