How to remove focus and selection from Listbox with a single “Click”?

from tkinter import *

root = Tk()
root.geometry("500x300")

def update(data):    
# Clear the listbox
    my_list.delete(0, END)

# Add toppings to listbox
    for item in data:
        my_list.insert(END, item)

def fillout(e):  # $$%%$$%%$$

    my_entry.delete(0, END)
    my_entry.insert(0, my_list.get(ANCHOR))

    my_list .selection_clear(0, END)  
    my_entry .focus_set()                     
    my_entry .icursor(END)                   

def check(e): 

    typed = my_entry.get()

    if typed == '':
        data = toppings
    else:
        data = []
        for item in toppings:
            if typed.lower() in item.lower():
                data.append(item)
    update(data)                


my_label = Label(root, text="Start", fg="grey")
my_label.pack(pady=20)

my_entry = Entry(root)
my_entry.pack()

my_list = Listbox(root, width=50)
my_list.pack(pady=40)

toppings = ["Pepperoni", "Peppers", "Mushrooms", "Cheese", "Onions"]

my_list.bind("<<ListboxSelect>>", fillout)
my_entry.bind("<KeyRelease>", check)

root.mainloop()

I am trying to remove the focus and deselect the widget (listbox) to the entry. In short, the behavior I want is that when selecting an option from the list box, remove all kinds of focus and instantly the insertion cursor is in the input. I’ve tried with (.focus_set () and selection_clear ()), but it doesn’t seem to work for me. I ask for your help and guidance please. Thanks for taking the time to read this…!

Answer

You need to wait to set the focus until after all other pending events have been processed. You can do that by using after_idle, like in the following example:

my_entry.after_idle(my_entry.focus_set)