I was trying to make the currently selected Listbox
item to be printed out. For example, when I select item "one", it should print out "one"
You could use this, it doesn't require the list box. So if you have multiple list boxes it will retrieve the value from any
from tkinter import*
root=Tk()
sizex = 600
sizey = 400
posx = 40
posy = 20
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
itemsforlistbox=['one','two','three','four','five','six','seven']
def CurSelet(event):
widget = event.widget
selection=widget.curselection()
picked = widget.get(selection[1])
print(picked)
mylistbox=Listbox(root,width=60,height=10,font=('times',13))
mylistbox.bind('<<ListboxSelect>>',CurSelet)
mylistbox.place(x=32,y=90)
for items in itemsforlistbox:
mylistbox.insert(END,items)
root.mainloop()
The line picked = widget.get(selection[1])
should be picked = widget.get(selection[0])
.
Otherwise, there will be an "index out of range" error.
This seems to work for me:
mylistbox.get(ANCHOR)
Based on your code, it will print out the current item.
as stated by user1576772 the correct answer should be :
mylistbox.get(ANCHOR)
The Problem with curselection()
is it returns the whole list currently selected each time.
consider a situation where you scroll through a Listbox and want always to get the last selected item forward or backward (not the last item in highlighted list , the last item pressed on by user )! curselection()
will give you all the currently selected items which is helpful but you will never know which item was selected last !
An item becomes active after you click on it—which means after your ListboxSelect
method returns. So, you're printing out whatever was active before this click (meaning, generally, what you clicked last time).
Also, given that you refer to "selected" numerous times, I think what you want is the selected value(s), not the active one, so you should be asking for that.
For a listbox with selectmode=SINGLE
or BROWSE
(the default, what you have) listbox, you can fix both of these trivially. Just change this:
mylistbox.get(ACTIVE)
to:
mylistbox.get(mylistbox.curselection())
If you need to handle MULTIPLE
or EXTENDED
, then of course there are anywhere from 0 to 7 selections instead of exactly 1, so you need to do something like:
values = [mylistbox.get(idx) for idx in mylistbox.curselection()]
print ', '.join(values)
While we're at it, I'm not sure why you were doing str((mylistbox.get(ACTIVE)))
, or even str(mylistbox.get(ACTIVE))
. The result of mylistbox.get
with a single index is going to be a string, the same one you inserted.