Reputation: 875
Is there a way to loop over items in a tkinter listbox, so I can check the first part of an item and delete and replace it with a new item if the two strings match?
for instance if I had:
{'breakfast':['bacon','eggs','beans'],
'lunch':['ham', 'cheese', 'bread'],
'dinner':['Steak','Potato','Vegetables']}
and this was displayed in a listbox using string formatting to:
breakfast: Bacon, Eggs, Beans
lunch: Ham, Cheese, Bread
dinner: Steak, Potato, Vegetables
if I change breakfast
to ['Cereal', 'Milk']
how would I change the entry in the listbox If I didn't know the index, and only had the dictionary key to go on?
Upvotes: 1
Views: 7358
Reputation: 6223
Use Listbox
's get
, delete
and insert
methods, together with enumerate
to get the index.
Assuming you did from Tkinter import *
:
for i, listbox_entry in enumerate(my_listbox.get(0, END)):
if listbox_entry == old_breakfast_string:
my_listbox.delete(i)
my_listbox.insert(i, new_breakfast_string)
If you did import Tkinter
, replace END
with Tkinter.END
.
In fact, if you're looking for an exact match (and you know the element is in the Listbox for sure), you don't even need an explicit loop, instead you can just use Python lists' index
method:
i = my_listbox.get(0, END).index(old_breakfast_string)
my_listbox.delete(i)
my_listbox.insert(i, new_breakfast_string)
Upvotes: 6