How to directly modify a specific item in a TKinter listbox?

Tkinter is a Python-based GUI application development library which is generally used to build useful functional desktop applications. The Listbox widget is another tkinter widget, which is used as a container to display a list of items in the form of a Listbox.

To define a list of items in a Listbox widget, you'll need to create a constructor of Listbox(root, width, height, **options). You can insert as many items as you want to display in the listbox.

Suppose you want to modify a specific item in a tkinter Listbox, then you can first create a button to select the item from the list you want to modify, and then call the delete() method to delete any existing values from it. Once the values are deleted, you can insert() a new item in the listbox.Let's take an example to understand how it works.


# 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

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


# Select the list item and delete the item first
# Once the list item is deleted,
# we can insert a new item in the listbox
def edit_current():
   for item in lb.curselection():
      lb.insert("end", "foo")

# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")

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


In this example, we have created a list of items using the Listbox widget. We have created a button named "Edit" which basically modifies the existing values of selected list items. Using this, you can replace/modify the values of any item in the list in the Listbox widget.


Once executed, it will produce the following output window −

Now, select an item from the list and click the "Edit" button. Suppose you select "item5" and click "Edit", then that particular entry will be replaced by "foo".

Updated on: 22-Dec-2021


Kickstart Your Career

Get certified by completing the course

Get Started