Selecting Selected line in listbox python tkinter
Question: Hi i have a question to ask regarding Python Tkinter Listbox. when i select
the value, what must i add into my code so that the Listbox would return the
value? There is no need for multiple selection. Or, can i add in a button to
execute a command, while putting the returned value from the listbox into the
command? I am using Python 2.7 and lis is the name of my array. Thank you for
your kind attention and help!

    
    
    master = Tk()
    
    listbox = Listbox(master)
    listbox.pack()
    
    listbox.insert(END, "Please select:")
    
    for p in lis:
        listbox.insert(END, p)
    
    master.mainloop()
    


Answer: For example you can add button to check selection

    
    
    from Tkinter import *
    
    def check_list():
        try:
            s = lb.selection_get()
            print 'selected:', s
        except:
            print 'no selection'
    
    master = Tk()
    
    lb = Listbox(master)
    lb.pack()
    
    lb.insert(END, "Please select:")
    for p in range(10):
        lb.insert(END, p)
    
    but = Button(master, text="Check", command=check_list)
    but.pack()
    
    master.mainloop()
    

* * *

if you need some argument in `command` then use `lambda`

    
    
    command=lambda:my_function(argument)
    

BTW: look out on argument in `command=` when you use it in `for` loop

This puts value `10` in place of `i` in all `my_function(i)`

    
    
    for i in range(10):
         ... command=lambda:my_function(i)
    

This works as expected

    
    
    for i in range(10):
         ... command=lambda x=i:my_function(x)
    

* * *

**EDIT:**

`lb.selection_get()` gives text from listbox (and use `\n` to seperate
elements in multiselection) and raise error if there is no selection.

`lb.curselection()` gives list of indexes and empty list if there is no
selection.

    
    
    def check_list_2():
        s = lb.curselection()
        if not s:
            print 'no selection'
        else:
            for x in s:
                print 'selected index:', x
                print 'selected text:', lb.get(x)
    

