Python Tkinter multiple selection Listbox

后端 未结 3 1027
梦谈多话
梦谈多话 2021-01-02 13:32

I tried a search on here but not come across the correct answer.
I have a listbox which is setup with selection=\'multiple\'. I then try to obtain a list

相关标签:
3条回答
  • 2021-01-02 13:57

    It seems the correct way to get a list of selected items in a Tkinter listbox is to use self.rightBT3.curselection(), which returns a tuple containing the zero-based index of the selected lines. You can then get() each line using those indices.

    (I haven't actually tested this though)

    0 讨论(0)
  • 2021-01-02 14:00

    I find the above solution a little bit "obscure". Specially when we are dealing here with programers that are learning the craft or learning python/tkinter.

    I came out with, what I think, a more explanatory solution, which is the following. I hope that this works out better for you.

    #-*- coding: utf-8 -*-
    # Python version 3.4
    # The use of the ttk module is optional, you can use regular tkinter widgets
    
    from tkinter import *
    from tkinter import ttk
    
    main = Tk()
    main.title("Multiple Choice Listbox")
    main.geometry("+50+150")
    frame = ttk.Frame(main, padding=(3, 3, 12, 12))
    frame.grid(column=0, row=0, sticky=(N, S, E, W))
    
    valores = StringVar()
    valores.set("Carro Coche Moto Bici Triciclo Patineta Patin Patines Lancha Patrullas")
    
    lstbox = Listbox(frame, listvariable=valores, selectmode=MULTIPLE, width=20, height=10)
    lstbox.grid(column=0, row=0, columnspan=2)
    
    def select():
        reslist = list()
        seleccion = lstbox.curselection()
        for i in seleccion:
            entrada = lstbox.get(i)
            reslist.append(entrada)
        for val in reslist:
            print(val)
    
    btn = ttk.Button(frame, text="Choices", command=select)
    btn.grid(column=1, row=1)
    
    main.mainloop()
    

    Please note that the use ot the ttk themed widgets is completely optional. You can use normal tkinter's widgets.

    0 讨论(0)
  • 2021-01-02 14:13

    To get a list of text items selected in a listbox, I find the below solution to be the most elegant:

    selected_text_list = [listbox.get(i) for i in listbox.curselection()]
    
    0 讨论(0)
提交回复
热议问题