Depending on the configuration, a list box can be set to allow users to select either a single option or multiple options from the available choices. When working with large datasets, lists can become quite long, making a filter essential for efficiently selecting specific values. The filter allows you to narrow down the list by typing a text string into the search field above the list—values that do not match the string are removed from view. This particular filter requires pressing the "Enter" key to initiate the search. In Python's Tkinter library, a list box is represented by the Listbox widget.
From a programmer's perspective, we work with two data collections: main_data (the complete dataset) and filtered_data (the subset matching the search criteria). We filter the data using Python's str.find(sub[, start[, end]]) method, which returns the lowest index where a substring sub is found within a string slice. Since we always search from the beginning of each string, we omit the optional start and end arguments. We scan all strings in main_data, copy matching items to filtered_data, and display the results in the list box. If the user removes the filter by clearing the search box, we restore the original main_data to the list box.
from tkinter import Tk, Listbox, Entry, StringVar, END, mainloop
def cb_search(event):
sstr = search_str.get()
listbox.delete(0, END)
# If filter removed show all data
if sstr == "":
fill_listbox(main_data)
return
filtered_data = list()
for item in main_data:
if item.find(sstr) >= 0:
filtered_data.append(item)
fill_listbox(filtered_data)
def fill_listbox(ld):
for item in ld:
listbox.insert(END, item)
main_data = ["one", "two", "three", "twenty two"]
# GUI
master = Tk()
listbox = Listbox(master)
listbox.pack()
fill_listbox(main_data)
search_str = StringVar()
search = Entry(master, textvariable=search_str, width=10)
search.pack()
search.bind('', cb_search)
mainloop()
This approach can also be applied to other Tkinter widgets that display data in list or array formats, such as the Treeview widget. The code presented here is one of the simplest methods for filtering data in a list box. Two potential optimizations could enhance its functionality: first, searching within the already filtered data currently displayed in the list box, and second, making the search more interactive by updating results with each keystroke instead of requiring the user to press the "Enter" button.