Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_autocomplete_tkinter_code.py
- from typing import List
- def autocomplete(entry: tk.Entry, options: List[str]):
- def complete(event):
- # Get the current text in the entry widget
- text = entry.get()
- # If there is no text, do nothing
- if not text:
- return
- # Get a list of matching options
- matches = [option for option in options if option.startswith(text)]
- # If there is only one match, insert it into the entry
- if len(matches) == 1:
- entry.delete(0, tk.END)
- entry.insert(0, matches[0])
- # If there are multiple matches, show a list of options
- elif len(matches) > 1:
- # Create a listbox to display the options
- listbox = tk.Listbox(entry.master, height=len(matches))
- listbox.pack()
- # Insert the options into the listbox
- for option in matches:
- listbox.insert(tk.END, option)
- # Set the listbox to the current position of the entry widget
- entry_x, entry_y, entry_width, entry_height = entry.bbox(tk.INSERT)
- listbox_x = entry_x
- listbox_y = entry_y + entry_height
- listbox.place(x=listbox_x, y=listbox_y)
- # Select the first item in the list
- listbox.selection_set(0)
- # Bind the listbox to the key and mouse events of the entry widget
- entry.bind('<KeyRelease>', update_list)
- entry.bind('<Button-1>', hide_list)
- listbox.bind('<Double-Button-1>', select_item)
- def update_list(event):
- # Get the current text in the entry widget
- text = entry.get()
- # If there is no text, delete the listbox and do nothing
- if not text:
- try:
- listbox.destroy()
- except:
- pass
- return
- # Update the list of options based on the current text
- matches = [option for option in options if option.startswith(text)]
- # If there are no matches, delete the listbox and do nothing
- if not matches:
- try:
- listbox.destroy()
- except:
- pass
- return
- # Update the listbox with the new matches
- listbox.delete(0, tk.END)
- for option in matches:
- listbox.insert(tk.END, option)
- # Select the first item in the list
- listbox.selection_set(0)
- def hide_list(event):
- # Hide the listbox and delete it
- try:
- listbox.destroy()
- except:
- pass
- def select_item(event):
- # Insert the selected item into the entry widget
- entry.delete(0, tk.END)
- entry.insert(0, listbox.get(tk.ACTIVE))
- # Hide the listbox and delete it
- try:
- listbox.destroy()
- except:
- pass
- # Bind the autocomplete function to the key event of the entry widget
- entry.bind('<KeyRelease>', complete)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement