Search code examples
pythontkinterlistbox

How do you get all the contents from a tkinter "multiple select" Listbox?


You can see here that I am creating a tkinter ListBox and populating it with 3 items. All I need to do is be able to record what the user has selected when they press the button!

I know that when you click the Button, bigListbox.curselection() gets the indexes of the items correctly and inserts them into the show label.

But I need to actually collect the currently selected strings and save them to a file upon clicking send.

def showSelected():
    show.config(text=bigListbox.curselection())


bigListbox = Listbox(rootWindow, selectmode="multiple")
bigListbox.pack()



# Load workstations from file
bigArr=["MYHSS", "MY", "MORE", "Aloysius"]

myIndex = len(bigArr)

for index in range(0, myIndex):
    bigListbox.insert(myIndex, bigArr[index])


Button(rootWindow, text='Send', command=showSelected).pack(pady=20)


show = Label(rootWindow)
show.pack()

Solution

  • You can use .get() of Listbox to get the string at specified index:

    def showSelected():
        # create a comma separated list of selected items
        items = ", ".join(bigListbox.get(idx) for idx in bigListbox.curselection())
        show.config(text=items)