As a developer, I recently faced the challenge of implementing a user-friendly search feature in my Tkinter application. In this tutorial, I will explain how to create a search box with autocomplete in Python Tkinter library. After researching and experimenting, I discovered an effective solution and I will share my findings with suitable examples and screenshots.
Create a Search Box with Autocomplete in Python Tkinter
Imagine you’re building a Tkinter application that requires a search functionality. You want users to be able to type in a search query and receive relevant suggestions as they type. This enhances the user experience and helps them find the desired information quickly.
Read How to Create and Customize Listboxes in Python Tkinter?
Step 1: Set Up the Tkinter Window
First, let’s create a basic Tkinter window to host our search box. Here’s an example:
import tkinter as tk
window = tk.Tk()
window.title("Search Box Example")
window.geometry("400x300")
window.mainloop()This code creates a simple window with a title and specified dimensions.
Check out How to Create Message Boxes with Python Tkinter?
Step 2: Create the Search Box
Next, we’ll add an entry widget to serve as our search box. We’ll also create a list box to display the autocomplete suggestions. Here’s the code:
search_var = tk.StringVar()
search_entry = tk.Entry(window, textvariable=search_var, font=("Arial", 12))
search_entry.pack()
suggestion_list = tk.Listbox(window, font=("Arial", 12))
suggestion_list.pack()In this code snippet, we create an Entry widget called search_entry and a Listbox widget called suggestion_list. The search_var is a StringVar that will hold the user’s input in the search box.
Step 3: Implement Autocomplete Functionality
Now comes the exciting part – implementing the autocomplete functionality. We’ll define a function that updates the suggestion list based on the user’s input. Here’s an example:
def update_suggestions(*args):
search_term = search_var.get()
suggestions = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
matching_suggestions = [suggestion for suggestion in suggestions if suggestion.lower().startswith(search_term.lower())]
suggestion_list.delete(0, tk.END)
for suggestion in matching_suggestions:
suggestion_list.insert(tk.END, suggestion)
search_var.trace("w", update_suggestions)In this code, the update_suggestions function is called whenever the user types in the search box. It retrieves the current search term using search_var.get(). We have a predefined list of suggestions (in this example, U.S. city names).
The function then filters the suggestions based on the search term, creating a new list called matching_suggestions. It clears the existing suggestions in the list box suggestion_list.delete(0, tk.END) and inserts the matching suggestions using a loop.
Finally, we use search_var.trace("w", update_suggestions) to bind the update_suggestions function to the search_var. Whenever the value search_var changes, the function is automatically called.
Read How to Create a Text Box in Python Tkinter?
Step 4: Handle Selection and Search
To complete our search box functionality, we need to handle the selection of a suggestion and perform the actual search. Here’s an example of how to do that:
def select_suggestion(event):
selected_suggestion = suggestion_list.get(suggestion_list.curselection())
search_var.set(selected_suggestion)
perform_search()
def perform_search():
search_term = search_var.get()
# Perform the search operation based on the search term
print("Performing search for:", search_term)
suggestion_list.bind("<<ListboxSelect>>", select_suggestion)
search_entry.bind("<Return>", lambda event: perform_search())In this code, the select_suggestion function is called when the user selects a suggestion from the list box. It retrieves the selected suggestion using suggestion_list.get(suggestion_list.curselection()) and sets the search_var to the selected value. It then calls the perform_search function to initiate the search operation.
The perform_search function is where you would implement the actual search logic based on the search term. In this example, we simply print the search term to demonstrate the functionality.
We bind the select_suggestion function to the list box’s <<ListboxSelect>> event, which is triggered when an item is selected. Additionally, we bind the perform_search function to the <Return> event of the search entry, allowing users to initiate the search by pressing the Enter key.
Check out How to Create Checkboxes in Python Tkinter?
Put It All Together
Here’s the complete code for our search box with autocomplete functionality:
import tkinter as tk
window = tk.Tk()
window.title("Search Box Example")
window.geometry("400x300")
search_var = tk.StringVar()
search_entry = tk.Entry(window, textvariable=search_var, font=("Arial", 12))
search_entry.pack()
suggestion_list = tk.Listbox(window, font=("Arial", 12))
suggestion_list.pack()
def update_suggestions(*args):
search_term = search_var.get()
suggestions = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
matching_suggestions = [suggestion for suggestion in suggestions if suggestion.lower().startswith(search_term.lower())]
suggestion_list.delete(0, tk.END)
for suggestion in matching_suggestions:
suggestion_list.insert(tk.END, suggestion)
search_var.trace("w", update_suggestions)
def select_suggestion(event):
selected_suggestion = suggestion_list.get(suggestion_list.curselection())
search_var.set(selected_suggestion)
perform_search()
def perform_search():
search_term = search_var.get()
# Perform the search operation based on the search term
print("Performing search for:", search_term)
suggestion_list.bind("<<ListboxSelect>>", select_suggestion)
search_entry.bind("<Return>", lambda event: perform_search())
window.mainloop()You can look at the output in the screenshot below.

Check out How to Convert a List to an Array in Python?
Implement Search Functionality in Python Tkinter
Let us learn some implementation of search functionality in Python Tkinter.
1. Search Button
The search button is used for submitting the search. When we enter text in the search box. After entering the text click on the search button for submitting the search and find the text which we want.
from tkinter import *
ws = Tk()
Frm = Frame(ws)
Label(Frm,text='Enter to search:').pack(side=LEFT)
modify = Entry(Frm)
modify.pack(side=LEFT, fill=BOTH, expand=1)
modify.focus_set()
buttn = Button(Frm, text='Search')
buttn.pack(side=RIGHT)
Frm.pack(side=TOP)
txt = Text(ws)
txt.insert('1.0','''Enter Text here...''')
txt.pack(side=BOTTOM)
def find():
txt.tag_remove('found', '1.0', END)
ser = modify.get()
if ser:
idx = '1.0'
while 1:
idx = txt.search(ser, idx, nocase=1,
stopindex=END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(ser))
txt.tag_add('found', idx, lastidx)
idx = lastidx
txt.tag_config('found', foreground='blue')
modify.focus_set()
buttn.config(command=find)
ws.mainloop()You can look at the output in the screenshot below.

After entering the text, click on the search button to submit the search and find the text that you want.
Check out How to Convert a Dictionary to a List in Python?
2. Listbox Search
A list box is used to display a list of items to the user and permits the user to select the items from a list. Users click inside the list box on an item to select it.
from tkinter import *
def Scankey(event):
val = event.widget.get()
print(val)
if val == '':
data = list
else:
data = []
for item in list:
if val.lower() in item.lower():
data.append(item)
Update(data)
def Update(data):
listbox.delete(0, 'end')
# put new data
for item in data:
listbox.insert('end', item)
list = ('C','C++','Java',
'Python','Perl',
'PHP','ASP','JS' )
ws = Tk()
entry = Entry(ws)
entry.pack()
entry.bind('<KeyRelease>', Scankey)
listbox = Listbox(ws)
listbox.pack()
Update(list)
ws.mainloop()You can look at the output in the screenshot below.

Read Create a To-do list in Python Django
3. Combobox Search
A combo box is defined as a dropdown list or list box. We can either type the item name that we want to search or directly select the item from the dropdown list menu.
from tkinter import *
from tkinter.ttk import Combobox
ws = Tk()
ws.title("Python Guides")
ws.geometry("200x200")
def search_items():
search_value = variable.get()
if search_value == "" or search_value == " ":
combo['values'] = item_names
else:
value_to_display = []
for value in item_names:
if search_value in value:
value_to_display.append(value)
combo['values'] = value_to_display
item_names = list([str(a) for _ in range(100) for a in range(10)])
combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()
variable=StringVar()
entry1 = Entry(ws, textvariable=variable)
entry1.pack()
button = Button(ws, text="search", command=search_items)
button.pack()
ws.mainloop()You can look at the output in the screenshot below.

If we click on the item they want to choose. The chosen item is shown in the entry box.
Check out Python Tkinter search box
Conclusion
In this tutorial, I explained how to create a search box with autocomplete in Python Tkinter. I discussed steps to create a search box with autocomplete and by putting it all together we run the code. I also discussed how to implement a search functionality in Python Tkinter.
You may like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.