How to edit a Listbox item in Tkinter?

Tkinter Listbox widget is generally used to create a list of items. It can store a list of numbers, characters and support many features like selecting and editing the list items.

To edit the Listbox items, we have to first select the item in a loop using listbox.curselection() function and insert a new item after deleting the previous item in the listbox. To insert a new item in the listbox, you can use listbox.insert(**items) function.


In this example, we will create a list of items in the listbox widget and a button will be used for editing the selected item in the list.

# 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="purple2", foreground="white", font=('Times 13'), selectbackground="black")


# 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():
   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).pack()



Running the above code will allow you to select and edit the list items.

You can configure the list of items by clicking the "Edit" button.

Updated on: 19-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started