Introduction
Basic Widgets
Toplevel Widgets
Geometry Management
Binding Functions
Working with Images in Tkinter
Tkinter Advance
Applications and Projects
Autocompleting ComboBox in Python using the Tkinter library can be accomplished with the ttk.Combobox
widget. To make it autocomplete, you'll need to bind it to keypress events and update the available values based on the user's input.
Here's a step-by-step tutorial:
Setting up the basic GUI with Tkinter:
We will start by setting up a basic window using Tkinter
.
import tkinter as tk from tkinter import ttk root = tk.Tk() root.title("Autocomplete ComboBox") root.geometry("300x200")
Creating the AutocompleteCombobox class:
This class will handle the autocompletion feature.
class AutocompleteCombobox(ttk.Combobox): def set_completion_list(self, completion_list): self._completion_list = sorted(completion_list) self._hits = [] self._hit_index = 0 self.position = 0 self.delete(0, tk.END) self.bind('<KeyRelease>', self.handle_keyrelease) self['values'] = self._completion_list def autocomplete(self, delta=0): if delta: del self.delete(self.position, tk.END) else: self.delete(self.position, tk.END) self._hit_index = 0 _hits = [] for item in self._completion_list: if item.lower().startswith(self.get().lower()): _hits.append(item) if _hits != self._hits: self._hit_index = 0 self._hits = _hits if _hits: self._hit_index = (self._hit_index + delta) % len(_hits) self.delete(0, tk.END) self.insert(0, _hits[self._hit_index]) self.select_range(self.position, tk.END) def handle_keyrelease(self, event): if event.keysym == "BackSpace": self.delete(self.index(tk.INSERT), tk.END) self.position = self.index(tk.END) if event.keysym == "Left": self.delete(self.index(tk.INSERT), tk.END) self.position = self.index(tk.END) if event.keysym == "Right": self.position = self.index(tk.END) self.delete(self.position, tk.END) if len(event.keysym) == 1: self.delete(self.index(tk.INSERT), tk.END) self.position = self.index(tk.END) self.autocomplete()
Using the AutocompleteCombobox:
Now you can add items to the ComboBox and see the autocompletion in action.
combo = AutocompleteCombobox(root) combo.set_completion_list(['apple', 'banana', 'pear', 'pineapple', 'peach', 'plum', 'pomegranate']) combo.pack(pady=50)
Run the main loop:
root.mainloop()
When you combine all the code snippets above and run the script, you'll get a Tkinter window with an autocompleting ComboBox. Try typing any letter, and you'll see the ComboBox try to autocomplete based on the items in the list.
How to add autocomplete functionality to Tkinter ComboBox:
from tkinter import ttk, Tk def on_select(event): current_input = combo.get() # Implement autocomplete logic here suggestions = ["Option 1", "Option 2", "Option 3"] filtered_suggestions = [s for s in suggestions if current_input.lower() in s.lower()] combo['values'] = filtered_suggestions root = Tk() combo = ttk.Combobox(root, values=[]) combo.pack() combo.bind('<KeyRelease>', on_select) root.mainloop()