Posts: 302
Threads: 135
Joined: Aug 2018
Sep-13-2026, 07:59 AM
(This post was last modified: Nov-19-2026, 09:28 AM by Winfried.)
Hello,
A search through Google and the archives here returned nothing.
Is it possible to edit items in a listbox, either through wx.ListBox or the wx.ItemContainer? I'd like to append something to the strings as I perform a task in a loop:
items = [self.lb1.GetString(i) for i in range(self.lb1.GetCount())]
for item in items:
#do something
#modify string in listbox Cheers,
--
Edit: Unless there's a way to get the item's position in the original list, I'll increment my own counter and use the SetString() method:
items = [self.lb1.GetString(i) for i in range(self.lb1.GetCount())]
index = 0
for item in items:
#do stuff
self.lb1.SetString(index, f"{item} DONE")
index += 1--
Edit: Simpler way to get items:
index = 0
for item in self.lb1.GetStrings():
self.lb1.SetString(index, f"{item} DONE")
index += 1
Posts: 12,167
Threads: 499
Joined: Sep 2016
Here's the AI answer from Gemini, edited only to fit forum:
In Python's Tkinter library, a standard Listbox widget does not support direct in-place editing by default. However, you can easily modify its content using two standard approaches: [1]
- The Delete & Insert Method: You capture the selected item's index, delete it, and insert the modified text back at that exact position.
- The List Variable Method: You bind a mutable Python StringVar list to the listbox and modify the underlying data directly. [2, 3, 4, 5]
------------------------------
Method 1: Delete and Re-Insert (Recommended)
This is the most straightforward method. You use curselection() to get the current index, delete the old item, and insert the new text. [2, 3]
Here is a complete, runnable example that updates the selected item using an Entry box and an Update button:
import tkinter as tk
def update_item():
try:
# 1. Get the index of the selected item
selected_index = listbox.curselection()[0]
# 2. Get the new text from the entry box
new_text = entry.get()
# 3. Delete the old item and insert the new one at the same index
listbox.delete(selected_index)
listbox.insert(selected_index, new_text)
# Optional: Keep the newly edited item highlighted
listbox.select_set(selected_index)
except IndexError:
# Handles the case where no item is selected
print("Please select an item to edit.")
root = tk.Tk()
root.title("Edit Listbox Item")
root.geometry("300x250")
# Create Listbox and populate itlistbox = tk.Listbox(root)
listbox.pack(pady=10)for item in ["Apple", "Banana", "Cherry"]:
listbox.insert(tk.END, item)
# Create Entry widget to type the replacement textentry = tk.Entry(root)
entry.pack(pady=5)
entry.insert(0, "New Value")
# Create Update Buttonupdate_btn = tk.Button(root, text="Update Selected", command=update_item)
update_btn.pack(pady=5)
root.mainloop()------------------------------
Method 2: Double-Click to Inline Edit (Advanced)
If you want a more modern user experience where double-clicking an item opens the entry box directly over it, you can dynamically create a temporary Entry widget over the selected row. [1]
Here is how you can implement an inline-editable listbox:
You can create a custom subclass of tk.Listbox that binds a double-click event (<Double-1>) to locate the clicked item's bounding box via self.bbox(index), render a temporary Entry widget over it, and update the listbox item upon pressing <Return> or losing focus (<FocusOut>). You can find the full implementation code in the referenced web document. [1]
------------------------------
Summary of Key Functions
- listbox.curselection(): Returns a tuple containing the index of the selected item(s).
- listbox.delete(index): Removes the item at the specified position.
- listbox.insert(index, element): Places the new item back into the listbox at the specified position. [3, 6]
Would you like help adapting this to a specific layout style, or perhaps connecting the list items to an external database or file so updates save permanently?
[1] [ https://stackoverflow.com]( https://stackoverflow.com/questions/6460...dit-in-gui)
[2] [ https://stackoverflow.com]( https://stackoverflow.com/questions/1422...er-listbox)
[3] [ https://www.tutorialspoint.com]( https://www.tutorialspoint.com/article/h...er-listbox)
[4] [ https://tk-tutorial.readthedocs.io]( https://tk-tutorial.readthedocs.io/en/la...stbox.html)
[5] [ https://tkdocs.com]( https://tkdocs.com/tutorial/morewidgets.html)
[6] [ https://www.youtube.com]( https://www.youtube.com/watch?v=vjR45AHBprk)
Posts: 302
Threads: 135
Joined: Aug 2018
(Can't figure out how the Quote feature works in this forum)
> In Python's Tkinter library,
This is for wxPython.
Posts: 1,357
Threads: 157
Joined: Jul 2017
Sep-14-2026, 06:36 AM
(This post was last modified: Sep-14-2026, 06:36 AM by Pedroski55.)
This is for tkinter.
listbox so-called because it represents a Python list.
Here you can edit items in the list by using an entry box and clicking a button:
from tkinter import *
from tkinter import ttk
def appp():
win = Tk()
win.geometry("700x400")
lb = Listbox(win, width=50, height=8)
lb.pack(pady=10)
entry = Entry(win, width=50)
entry.pack(pady=5)
def modify_selected():
selection = lb.curselection()
if selection:
index = selection[0]
new_value = entry.get()
if new_value:
lb.delete(index)
lb.insert(index, new_value)
entry.delete(0, END)
items = ["Apple", "Banana", "Orange", "Grapes", "Mango"]
for item in items:
lb.insert(END, item)
ttk.Button(win, text="Modify Selected", command=modify_selected).pack(pady=5)
win.mainloop()I wanna convert to Chinese, so select Apple, enter 苹果 in the entry box,click the button, done!
There are various methods of selection.
tk.SINGLE only allows selection of 1 line and no dragging.
Posts: 7,010
Threads: 22
Joined: Feb 2020
Sep-23-2026, 03:48 PM
(This post was last modified: Sep-23-2026, 03:48 PM by deanhystad.)
I would collect items in a list and use ListBox.Set(choices) to update the listbox. This example creates listbox class that treats choices and selections as properties. It also creates an inactive listbox for displaying choices and selections that cannot be changed by the user.
import wx
class EnhancedListBox(wx.ListBox):
"""ListBox with choices and selection properties."""
def __init__(self, master=None, choices=[], style=wx.LB_EXTENDED, **kwargs):
"""Initialize the ListDisplay widget.
Args:
master (wx.Window): The parent window.
choices (list): The list of choices to display.
style (int): The style of the listbox.
**kwargs: Additional keyword arguments passed to the wx.ListBox constructor.
"""
super().__init__(master, choices=choices, style=style, **kwargs)
@property
def choices(self):
"""Return choices as a list."""
return list(self.GetItems())
@choices.setter
def choices(self, value):
"""Set choices from a list."""
self.Set(value)
@property
def selection(self):
"""Return selection as list of selected choices."""
choices = self.GetItems()
return [choices[i] for i in self.GetSelections()]
@selection.setter
def selection(self, value):
"""Set selection from a list of selected choices."""
for index in self.GetSelections():
self.Deselect(index)
choices = self.GetItems()
for item in value:
try:
self.Select(choices.index(item))
except ValueError:
pass
class ListDisplay(EnhancedListBox):
"""A Listbox widget for displaying a list of items. User cannot change selection."""
def __init__(self, master=None, choices=[], **kwargs):
"""Initialize the ListDisplay widget.
Args:
master (wx.Window): The parent window.
choices (list): The list of choices to display.
**kwargs: Additional keyword arguments passed to the wx.ListBox constructor.
"""
super().__init__(master, choices=choices, **kwargs)
self.Bind(wx.EVT_LEFT_DOWN, lambda *args, **kwargs: None)
self.Bind(wx.EVT_KEY_DOWN, lambda *args, **kwargs: None)
class MainWindow(wx.Frame):
"""The main application window."""
def __init__(self, master, **kwargs):
super().__init__(master, title="List Boxes",**kwargs)
choices = [f"Item {i}" for i in range(1, 11)]
self.lists = [EnhancedListBox(self, choices), ListDisplay(self), ListDisplay(self, choices)]
row = wx.BoxSizer(wx.HORIZONTAL)
for x in self.lists:
row.Add(x, 1, wx.ALL | wx.EXPAND)
layout = wx.BoxSizer(wx.VERTICAL)
layout.Add(row, 1, wx.EXPAND)
self.SetSizer(layout)
self.lists[0].Bind(wx.EVT_LISTBOX, self._copy_selection)
def _copy_selection(self, event):
"""Copy selected choices to list 1, unselected choices to list 2."""
selected = self.lists[0].selection
self.lists[1].choices = selected
self.lists[2].choices = [x for x in self.lists[0].choices if x not in selected]
event.Skip()
app = wx.App()
window = MainWindow(None)
window.Show()
app.MainLoop()Using EnhancedListBox your label change code would look like this:
items = self.lb1.choices
for index, item in enumerate(items):
#do stuff
items[index] = f"{item} DONE"
self.lb1.choices = items
|