

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
# Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb = Listbox(win, width=100, height=10, font=('Times 13'), selectbackground="black") lb.pack() # 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() win.mainloop()
Output
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
- Related Questions & Answers
- How can I change the text of the Tkinter Listbox item?
- How to edit a Listbox item in Tkinter?
- Default to and select the first item in Tkinter Listbox
- How do I find out the size of a canvas item in Tkinter?
- How to directly modify a specific item in a TKinter listbox?
- How do I get rid of the Python Tkinter root window?
- How do I get the width and height of a Tkinter window?
- How do I get the 'state' of a Tkinter Checkbutton?
- How do I get the background color of a Tkinter Canvas widget?
- How do I get the src of an image in Selenium?
- How to clear a Tkinter ListBox?
- Is it possible to color a specific item in a Tkinter Listbox widget?
- How to fully change the color of a Tkinter Listbox?
- How to get the index of selected option in Tkinter Combobox?
- How do I get an event callback when a Tkinter Entry widget is modified?
Advertisements