Tkinter weird listbox behavior

Question:

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?

Asked By: Gummi

||

Answers:

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)
Answered By: mamg2909

I’ve managed to fix this with an if statement in both functions, checking if the item in the listbox has no name.

if selectedItem != '':

Used here:

def possibleClicked(stuff):
    global curselect
    if possibleListbox.curselection():
        curselect = possibleListbox.curselection()
    selectedItem = possibleListbox.get(curselect)
    possibleListbox.delete(curselect)
    if selectedItem != '': #here
        selectedListbox.insert(tkinter.END, selectedItem)
def selectedClicked(stuff):
    global curselect
    if selectedListbox.curselection():
        curselect = selectedListbox.curselection()
    selectedItem = selectedListbox.get(curselect)
    selectedListbox.delete(curselect)
    if selectedItem != '': #here
        possibleListbox.insert(tkinter.END, selectedItem)
Answered By: Gummi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.