循环 tkinter 列表框

Loop over tkinter Listbox

有没有办法循环遍历 tkinter 列表框中的项目,这样我就可以检查项目的第一部分,如果两个字符串匹配,则删除并用新项目替换它?

例如,如果我有:

{'breakfast':['bacon','eggs','beans'],
 'lunch':['ham', 'cheese', 'bread'],
 'dinner':['Steak','Potato','Vegetables']}

这显示在列表框中,使用的字符串格式为:

breakfast: Bacon, Eggs, Beans
lunch: Ham, Cheese, Bread
dinner: Steak, Potato, Vegetables

如果我将 breakfast 更改为 ['Cereal', 'Milk'] 我将如何更改列表框中的条目 如果我不知道索引,并且只知道要继续的字典键?

使用Listboxget, delete and insert方法,结合enumerate获取索引。

假设你做到了 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)

如果您这样做了 import Tkinter,请将 END 替换为 Tkinter.END

事实上,如果您正在寻找完全匹配(并且您肯定知道该元素在列表框中),您甚至不需要显式循环,而是可以使用 Python 列出“index 方法:

i = my_listbox.get(0, END).index(old_breakfast_string)
my_listbox.delete(i)
my_listbox.insert(i, new_breakfast_string)