pythontkinterlistboxlistboxitem

return multiple values from list box tkinter python


I'm trying to return the selection value/s from a list box.

first, I have a combo box in which the user needs to select the area ( A, B, C....)
After the area is being selected, a list box appeared on the widget and the user needs to select other options. When I try to select values from the list box it prints nothing, empty list.

How do I return the other options?

GUI


Solution

  • Since you get the selected items just after area_listbox is created, you will get nothing as nothing is selected.

    You can do it in a function triggered by a button instead. Also better create the listbox outside sheetChosenLabel() and update its content inside the function.

    Below is an example based on your posted code:

    import tkinter as tk
    from tkinter import ttk
    
    # sample data
    Sheets = {
        'A': (f'A{i}' for i in range(1, 10)),
        'B': (f'B{i}' for i in range(1, 20)),
        'C': (f'C{i}' for i in range(1, 8)),
    }
    
    
    def sheetChosenLabel(event):
        # update listbox based on selected area
        area = combo_sheet.get()
        area_listbox.delete(0, tk.END)
        for item in Sheets[area]:
            area_listbox.insert(tk.END, item)
    
    
    def check_result():
        # get and show the selected items in listbox
        result = [area_listbox.get(i) for i in area_listbox.curselection()]
        print(result)
    
    
    root = tk.Tk()
    
    frame3 = tk.Frame(root)
    frame3.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)
    
    combo_sheet = ttk.Combobox(frame3, values=list(Sheets.keys()), state='readonly')
    combo_sheet.pack(padx=10, pady=5)
    combo_sheet.bind('<<ComboboxSelected>>', sheetChosenLabel)
    
    area_listbox = tk.Listbox(frame3, bg='PowderBlue', font='Arial 9', relief='sunken', selectmode=tk.MULTIPLE)
    area_listbox.pack(padx=10, pady=5)
    
    check_button = tk.Button(frame3, text='Check', command=check_result)
    check_button.pack(padx=10, pady=5)
    
    root.mainloop()