Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I change the text of the Tkinter Listbox item?
To display a list of items in the application, Tkinter provides a Listbox widget. It is used to create a list of items vertically. When we want to change the text of a specific Listbox item, we have to first select the item by iterating over the listbox.curselection() and insert a new item after deletion. To insert an item in the list, you can use listbox.insert().
Example
Here's a complete example that demonstrates how to change the text of a selected Listbox item ?
# Import the required libraries
from tkinter import *
from tkinter import ttk
# 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)
lb.pack(expand=True, fill=BOTH)
# Define a function to edit the listbox item
def edit():
for item in lb.curselection():
lb.delete(item)
lb.insert(item, "Updated Item")
# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")
# Add a Button To Edit the Listbox Item
ttk.Button(win, text="Edit", command=edit).pack()
win.mainloop()
How It Works
The edit() function works by:
-
lb.curselection()returns a tuple of selected item indices -
lb.delete(item)removes the item at the specified index -
lb.insert(item, "Updated Item")inserts the new text at the same position
Alternative Approach
You can also create a more interactive version that prompts for new text ?
from tkinter import *
from tkinter import ttk, simpledialog
win = Tk()
win.geometry("700x350")
lb = Listbox(win)
lb.pack(expand=True, fill=BOTH)
def edit_item():
selection = lb.curselection()
if selection:
index = selection[0]
current_text = lb.get(index)
new_text = simpledialog.askstring("Edit Item", f"Current: {current_text}\nEnter new text:")
if new_text:
lb.delete(index)
lb.insert(index, new_text)
lb.insert("end", "Apple", "Banana", "Cherry", "Date", "Elderberry")
ttk.Button(win, text="Edit Selected", command=edit_item).pack()
win.mainloop()
Key Points
- Always check if an item is selected using
curselection() - Use the same index for deletion and insertion to maintain position
- The
insert()method can add multiple items at once - Consider user input validation for dynamic editing
Conclusion
To change Listbox item text, use delete() followed by insert() at the same index. This approach maintains the item's position while updating its content effectively.
