Get selected item in listbox and call another function storing the selected for it

how to get the selected item in a listbox tkinter
tkinter listbox multiple selection
how to get selection from listbox tkinter
get text from listbox tkinter
how to select from listbox in tkinter
tkinter listbox selection change
tkinter listbox selection changed
tkinter listbox double click

I have a canvas that calls createCategoryMeny(x) when it is clicked.

This function just creates a Toplevel() window,

def createCategoryMenu(tableNumber):

    ##Not interesting below:
    categoryMenu = Toplevel()
    categoryMenu.title("Mesa numero: " + str(tableNumber))
    categoryMenu.geometry("400x400+100+100")

    categoryMenu.focus()
    categoryMenu.grab_set()

    Label(categoryMenu, text="Elegir categoria \n Mesa numero: " + str(tableNumber)).pack()


    ## RELEVANT CODE BELOW:
    listbox = Listbox(categoryMenu, width=50, height=len(info.listaCategorias))
    listbox.pack(pady=20)

    for item in info.listaCategorias:
        listbox.insert(END, item)

    listbox.selection_set(first=0)

    ##My attempt to solve it
    callback = lambda event, tag= "ThisShouldBeTheSelected!!": do(event, tag)
    listbox.bind("<Double-Button-1>", callback)

Then the do function:

def do(event, tag):
    print tag

This successfully prints `"ThisShouldBeTheSelected!!"``.

And this is where I am utterly stuck.

I cant get the double clicked element (the selected one).

I want to pass it as tag=.

I have tried:

listbox.curselection()

Which always prints ('0',)

If I remove listbox.selection_set(first=0), I only get this: ()

So the questions are:

  • How can I get the selected item (the double clicked one)
  • (Not so important) Is it reasonable to pass it to the other function like I do?

Note:

I found this:

8.5. Why doesn't .listbox curselection or selection get return the proper item when I make a button binding to my listbox?

The best way to get the selected item during a button click event on a listbox is to use the following code:

bind .listbox { set item [%W get [%W nearest %y]] }

This ensures that the item under the pointer is what will be returned as item. The reason .listbox curselection can fail is because the items in curselection are not set until the Listbox class binding triggers, which is after the instance bindings by defaults. This is the same reason for which selection get can fail, but it will also fail if you set the -exportselection option to 0.

I'm not sure if it's helpful, I don't really understand what it is saying.


For one, don't use lambda. It's useful for a narrow range of problems and this isn't one of them. Create a proper function, they are much easier to write and maintain.

Once you do that, you can call curselection to get the current selection. You say you tried that but your example code doesn't show what you tried, so I can only assume you did it wrong.

As for the rather unusual advice to use nearest... all it's saying is that bindings you put on a widget happen before default bindings for that same event. It is the default bindings that set the selection, so when you bind to a single button click, your binding fires before the selection is updated by the default bindings. There are many ways around that, the best of which is to not bind on a single click, but instead bind on <<ListboxSelect>> which will fire after the selection has changed.

You don't have that problem, however. Since you are binding on a double-click, the selection will have been set by the default single-click binding and curselection will return the proper value. That is, unless you have your own single-click bindings that prevent the default binding from firing.

Here's a simple example that prints out the selection so you can see it is correct. Run it from the command line so you see stdout:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        lb = tk.Listbox(self)
        lb.insert("end", "one")
        lb.insert("end", "two")
        lb.insert("end", "three")
        lb.bind("<Double-Button-1>", self.OnDouble)
        lb.pack(side="top", fill="both", expand=True)

    def OnDouble(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        print "selection:", selection, ": '%s'" % value

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

python, I have a canvas that calls createCategoryMeny(x) when it is clicked. This function just creates a Toplevel() window, To determine the items that are selected, you can use the Selected property of the list box. The Selected property of a list box is an array of values where each value is either True (if the item is selected) or False (if the item is not selected). For example, if the list contains the seven days of the week and Sunday, Tuesday, and Saturday


For spyder and python 3.6 this following code worked.

import tkinter as tk
root = tk.Tk()
root.geometry("612x417")
root.title("change label on listbox selection")
root.resizable(0,0)
root.configure(background='lightgrey')


#Show selected currency for from in label
frmcur_text = tk.StringVar()
frmcur = tk.Label(root, textvariable=frmcur_text, font="Helvetica 10 bold", anchor='w', background='lightgrey').place(x=195,y=50)

def onselect(evt):
    # Note here that Tkinter passes an event object to onselect()

    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
#    print ('You selected item %d: "%s"' % (index, value))
    frmcur_text.set(value)

#Create listboxes for xurrency selection
listbox1 = tk.Listbox(root, font="Helvetica 11 bold", height=3, width=10)
listbox2 = tk.Listbox(root, font="Helvetica 11 bold", height=3, width=10)
listbox1.place(x=300,y=50)
listbox2.place(x=300,y=125)


for i in range(20):
    i = i + 1
    listbox1.insert(1, i)
    listbox2.insert(1, i)


listbox1.bind('<<ListboxSelect>>', onselect)    

cs = listbox1.curselection()

frmcur_text.set(cs)

root.mainloop()

ListBox.SelectedItem Property (System.Windows.Forms), Gets or sets the currently selected item in the . Browsable(false)] public object SelectedItem { get; set; } The example code then reads the text of the item using the SelectedItem property and calls the FindString method on a different ListBox  If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { label1.Text = listBox1.SelectedItem.ToString(); }


While You have only one listbox to manage with, it's quite good to use something like this (Python 3):

import tkinter as tk

root = tk.Tk()
box = tk.Listbox(root)
box.insert(tk.END, 'First')
box.insert(tk.END, 'Second')
box.insert(tk.END, 'Third')
box.pack()


def onselect(event):
    w = event.widget
    idx = int(w.curselection()[0])
    value = w.get(idx)
    print(value)


box.bind('<<ListboxSelect>>', onselect)

root.mainloop()

But when You add another listbox, or\and meet a situation, where listbox loses its selection, IndexError is raised. To avoiding it, and to manage different callbacks for different listboxes I suggest something like this:

import tkinter as tk

root = tk.Tk()
box = tk.Listbox(root)
box.insert(tk.END, 'First')
box.insert(tk.END, 'Second')
box.insert(tk.END, 'Third')
box.pack()

box2 = tk.Listbox(root)
box2.insert(tk.END, 'First')
box2.insert(tk.END, 'Second')
box2.insert(tk.END, 'Third')
box2.pack()


def on_first_box(idx, val):
    print('First box idx: %s, value: %s' % (idx, val))


def on_second_box(idx, val):
    print('Second box idx: %s, value: %s' % (idx, val))


def onselect(event, listbox):
    w = event.widget
    try:
        idx = int(w.curselection()[0])
    except IndexError:
        return
    if listbox is box:
        return on_first_box(idx, w.get(idx))
    if listbox is box2:
        return on_second_box(idx, w.get(idx))


box.bind('<<ListboxSelect>>', lambda e: onselect(e, box))
box2.bind('<<ListboxSelect>>', lambda e: onselect(e, box2))

root.mainloop()

How to determine the items that are selected in a ListBox control, Other. Microsoft Rewards · Free downloads & security · Education · Store locations · Gift cards This article describes how to retrieve selected items from a ListBox control that makes it possible for you to select multiple values. item at a time, and the second method builds a list of all the selected items. You can use the Selected property to select items in a list box by using Visual Basic. For example, the following expression selects the fifth item in the list: Me!Listbox.Selected(4) = True Example. The following example uses the Selected property to move selected items in the lstSource list box to the lstDestination list box.


Get the selected items in a ListBox : ListBox « Forms « VBA / Excel , Get the selected items in a ListBox : ListBox « Forms « VBA / Excel / Access / Word. Add item to List Box: 2. Add names of all open workbooks to the list box: 3. Add items to ListBox: 4. Assign the data in a worksheet to RowSource of a ListBox: 5. Make sure the RowSource property is empty: 6. Select the items programmatically: 7. Get all selected items in a list box: 8. Evaluating Which Items Are Selected in the Multiselect List Box: 9.


Programming Excel with VBA: A Practical Real-World Guide, End If Next Now you need a way to store all ListBox-selected items in a variable so call the FilllstNames( ) procedure to fill lstNames with the new Name object or Names collections that hold references to different types of Excel objects. Set instruction to instantiate it or add some item with the Add method before trying​  The reason .listbox curselection can fail is because the items in curselection are not set until the Listbox class binding triggers, which is after the instance bindings by defaults. This is the same reason for which selection get can fail, but it will also fail if you set the -exportselection option to 0.


VB.Net - ListBox Control, To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Gets or sets the method in which items are selected in the list box. When the above code is executed and run using Start button available at the Fill the list and check workings of other buttons −. The problem is that when I select more than one item the message box shows the frist one I've selected and repeats the message EX: if I selected 3 items the message will appear 3 times with the first item