How to create a combo box with auto-completion in Tkinter?

TkinterPythonGUI-Programming

Tkinter Combobox widget is one of the useful widgets to implement dropdown menus in an application. It uses the combination of the Entry widget and ListBox widget on the top of it. We can select Menu items by typing the item name (if it exists in the Menu List) in the Entry field. However, sometimes, there might be cases when we need to use autocompletion to select the menu items.

In order to create an auto-completion Combobox, we will create a Listbox first to list out the menus and an Entry widget to display the selected Menu. You can bind the "Keyrelease" event with the entry widget to search for a particular keyword in the list. If the item exists, we will update the Listbox widget.

Example

In this example, we will create two functions such that,

  • A function check(e) will find if the entered item exists in the list or not. If the item matches with the entered keyword, we will update the Entry widget by inserting the particular data.
  • A function update(data) will update the Entry box by inserting the value in the Entry widget.
# Import the Required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win= Tk()

# Set the size of the window
win.geometry("700x350")

# Set the title of the window
win.title("Combobox- TutorialsPoint")

# Update the Entry widget with the selected item in list
def check(e):
   v= entry.get()
      if v=='':
      data= values
   else:
      data=[]
      for item in values:
         if v.lower() in item.lower():
            data.append(item)
   update(data)

def update(data):
   # Clear the Combobox
   menu.delete(0, END)
   # Add values to the combobox
   for value in data:
      menu.insert(END,value)


# Add a Label widget
label= Label(win, text= "Demo Combobox Widget", font= ('Helvetica 15
bold'), background= "green3")
label.pack(padx= 10, pady= 25)

# Add a Bottom Label
text= Label(win, text="Select a Programming Language")
text.pack(padx= 15,pady= 20)

# Create an Entry widget
entry= Entry(win, width= 35)
entry.pack()
entry.bind('<KeyRelease>',check)

# Create a Listbox widget to display the list of items
menu= Listbox(win)
menu.pack()

# Create a list of all the menu items
values= ['Python', 'C++', 'Java','Ruby on Rails', 'Rust',
'GoLang','Objective-C', 'C# ', 'PHP', 'Swift', 'JavaScript']

# Add values to our combobox
update(values)

# Binding the combobox onclick

win.mainloop()

Output

Running the above Python script will display a window with an Entry widget and a ListBox. Whenever we enter a Keyword, it will update the ListBox widget showing the result that matches with the entered keyword.

raja
Published on 07-Jun-2021 11:13:16
Advertisements