How do I get the index of an item in Tkinter.Listbox?


We use the Tkinter Listbox widget to create a list of items. Each item in the listbox has some indexes that are assigned to them sequentially in vertical order.

Let us suppose that we want to get the index of a clicked item in the listbox. Then, we have to first create a button that will capture the current selection of the items using list.curselection() method and then, we will print the index using the get() method.


# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window

# Create a Listbox widget
lb = Listbox(win, width=100, height=10, font=('Times 13'), selectbackground="black")

# Define a function to edit the listbox ite
def save():
   for item in lb.curselection():
      print("You have selected " + str(item+1))

# Add items in the Listbox
lb.insert("end", "A", "B", "C", "D", "E", "F")

# Add a Button To Edit and Delete the Listbox Item
Button(win, text="Save", command=save).pack()



If we run the above code, it will display a window containing a list of alphabets (A-F).

Select an item from the list and click the "Save" button to get the index of the selected item printed on the console.

You have selected 3
Published on 19-Jun-2021 08:31:56