Search code examples
pythontkinterlistbox

Tkinter weird listbox behavior


def possibleClicked(stuff):
    selectedItem = listbox.get(listbox.curselection())
    print(selectedItem)
    listbox.delete(listbox.curselection())
    listbox2.insert(tkinter.END, selectedItem)
    listbox.selection_clear(0, tkinter.END)

root = customtkinter.CTk()
root.geometry("650x400")
root.title("Bazaar Bot - Login")
root.resizable(False, False)



listbox = tkinter.Listbox(root, selectmode=tkinter.SINGLE, exportselection=False, width=15, height=10)
listbox.place(x=400,y=30)
listbox.bind("<<ListboxSelect>>", possibleClicked)

for i in settings.possible:
    listbox.insert(tkinter.END, i)

In the gif below, I'm spam clicking and the listbox elements do not always call the possibleClicked() function, moving my cursor seems to fix this for some reason.

gif of the problem

Not really sure what the error is, maybe something to do with the currently selected listbox element?


Solution

  • The problem here is that "double click" is a different event that "single click", so you are not actually triggering the <<ListboxSelect>> event. Also note that listbox.curselection() will return empty when double clicking. You need to redefine your code to account for the double click event:

    def possibleClicked(event):
        global curselect    
        if listbox.curselection():
            curselect = listbox.curselection()
    
        selectedItem = listbox.get(curselect)    
        listbox.delete(curselect)
        listbox.insert(tkinter.END, selectedItem)
        listbox.selection_clear(0, tkinter.END)
    
    global curselect
    curselect = ()
    root = tkinter.Tk()
    root.geometry("650x400")
    root.title("Bazaar Bot - Login")
    root.resizable(False, False)
    listbox = tkinter.Listbox(root, selectmode=tkinter.SINGLE, exportselection=False, width=15, height=10)
    listbox.place(x=400, y=30)
    listbox.bind("<<ListboxSelect>>", possibleClicked)
    listbox.bind("<Double-Button-1>", possibleClicked)