Tkinter ListBox Return the index of the selected item
The Tkinter ListBox curselection() method will pass back the index of the selected item.
Tkinter ListBox Return the index of the selected item Example#1
Create a list box, and when the option is selected, if you click the Print button you can print the selected content in the Python Shell window. The reader should note that line 4 of the program is to get the selected index item, if more than two items selected will be passed back in a tuple, so lines 4 and 5 can list the contents of the selected index item.
from tkinter import *
def callback(): # Print the selected item
indexs = lb.curselection()
for index in indexs: # Get index value
print(lb.get(index)) # Print the selected item
print(indexs)
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
root.geometry("300x250")
lb = Listbox(root,selectmode=MULTIPLE)
for fruit in fruits:
lb.insert(END,fruit)
lb.pack(pady=5)
btn = Button(root,text="Print",command=callback)
btn.pack(pady=5)
root.mainloop()
Output: