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 a specific Listbox item, then we have to first select the item by iterating over the listbox.curselection() and insert a new item after deletion. To insert a item in the list, you can use listbox.insert(**items).

Example

# 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 ite def edit():    for item in lb.curselection():       lb.delete(item)       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() win.mainloop()

Output

Executing the above code will display a window that contains a list of items.

Now, select an item from the list and click "Edit". It will edit the selected item in the list.

Updated on: 2021-06-18T13:56:14+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements