How to Create a Filter() Function in Python Tkinter?

As a developer working on a project for one of my clients, I faced the challenge of implementing a user-friendly search functionality in a Tkinter GUI application. By understanding the use of the filter() function and Tkinter’s intuitive interface, I successfully created a robust solution that enhances data accessibility for users. In this tutorial, I will explain how to create a filter() function in Python Tkinter with suitable examples.

Create a Filter() Function in Python Tkinter

Before getting into the implementation details, let’s first understand what the filter() function does in Python. The filter() function is a built-in function that allows you to efficiently filter elements from an iterable based on a specified condition. It takes two arguments: a function that defines the filtering condition and the iterable to be filtered. The filter() function returns an iterator containing only the elements that satisfy the given condition.

Read How to Display Images in Python Tkinter?

Employee Search Panel Using Tkinter Text Widget

To create a filter function in a Tkinter application, we need to combine the functionality of the filter() function with the user interface elements provided by Tkinter. Here’s a step-by-step guide on how to achieve this:

  1. Import the necessary modules:
import tkinter as tk
  1. Create a Tkinter window and input fields:
# Sample Employee Data
employees_list = ["Alice Johnson", "Bob Smith", "Charlie Brown", "David Wilson", "Emma Davis"]

window = tk.Tk()
window.title("Employee Search")

search_label = tk.Label(window, text="Search Employee:")
search_label.pack()

search_entry = tk.Entry(window)
search_entry.pack()
  1. Define the filter function:
def filter_employees():
    search_term = search_entry.get().lower()
    filtered_employees = list(filter(lambda x: search_term in x.lower(), employees_list))  # Filtering logic
    display_employees(filtered_employees)

In this example, the filter_employees() function retrieves the search term entered by the user, converts it to lowercase, and then uses the filter() function along with a lambda function to filter the employees list based on whether the search term is present in each employee’s name (case-insensitive).

  1. Display the filtered results:
def display_employees(employees):
    result_text.delete("1.0", tk.END)  # Clear previous results
    for employee in employees:
        result_text.insert(tk.END, employee + "\n")  # Display results

The display_employees() function takes the filtered list of employees and updates the Tkinter Text widget (result_text) to display the results.

  1. Add a search button and result display:
search_button = tk.Button(window, text="Search", command=filter_employees)
search_button.pack()

result_text = tk.Text(window, height=10, width=40)
result_text.pack()

window.mainloop()

You can see the output in the screenshot below.

Create a Filter() Function in Python Tkinter

Check out How to Create Scrollable Frames with Python Tkinter?

Employee Search Panel Using Tkinter Treeview Widget

This Tkinter application allows users to search for employees and display the results in a Treeview widget. The search dynamically filters employees based on their names and updates the table in real time.

import tkinter as tk
from tkinter import ttk

# Sample Employee Data
employees_list = [
    {"name": "Alice Johnson", "position": "Manager", "department": "HR"},
    {"name": "Bob Smith", "position": "Developer", "department": "IT"},
    {"name": "Charlie Brown", "position": "Designer", "department": "Marketing"},
    {"name": "David Wilson", "position": "Analyst", "department": "Finance"},
    {"name": "Emma Davis", "position": "Support", "department": "Customer Service"},
]

# Create main window
window = tk.Tk()
window.title("Employee Search")
window.geometry("500x300")

# Search label and entry field
search_label = tk.Label(window, text="Search Employee:")
search_label.pack()

search_entry = tk.Entry(window)
search_entry.pack()

# Function to filter employees
def filter_employees():
    query = search_entry.get().lower()
    
    # Clear previous results
    for row in result_tree.get_children():
        result_tree.delete(row)
    
    # Filter and display results
    for emp in employees_list:
        if query in emp["name"].lower():
            result_tree.insert("", tk.END, values=(emp["name"], emp["position"], emp["department"]))

# Search button
search_button = tk.Button(window, text="Search", command=filter_employees)
search_button.pack()

# Create Treeview widget
columns = ("Name", "Position", "Department")
result_tree = ttk.Treeview(window, columns=columns, show="headings")

# Define column headings
result_tree.heading("Name", text="Name")
result_tree.heading("Position", text="Position")
result_tree.heading("Department", text="Department")

# Pack Treeview
result_tree.pack(fill=tk.BOTH, expand=True)

# Run the main loop
window.mainloop()

You can see the output in the screenshot below.

Create a Filter() Function in Python Tkinter treeview

In the above example, the default blank column in the Treeview widget is removed because of the show="headings" parameter when creating the Treeview.

Read How to Use Colors in Python Tkinter?

Optimize the Filter Function

To optimize the filter function and improve its efficiency, we can consider the following tips:

  1. Use list comprehensions instead of filter(): While the filter() function is convenient, using list comprehensions can often be faster and more concise. Instead of using filter(), we can rewrite the filtering logic as follows:
filtered_employees = [employee for employee in employees if search_term in employee.lower()]
  1. Preprocess the data: If the list of employees is large and remains relatively static, we can preprocess the data by converting all the names to lowercase and storing them in a separate list. This way, we can avoid performing the case conversion for each search operation.
  2. Implement incremental searching: Instead of waiting for the user to click the search button, we can update the search results in real time as the user types. This can be achieved by binding the <KeyRelease> event to the search entry field and call the filter function whenever a key is released.

Check out How to Create a Text Box in Python Tkinter?

Conclusion

In this tutorial, I have explained how to create a filter() function in Python Tkinter. I discussed about filter() function in Python Tkinter, In the above examples I covered how to define the filter function, add a search button, use text widget and treeview widget

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.