Removing a selection from a listbox, as well as remove it from the list that provides it

匆匆过客 提交于 2021-02-09 01:51:35

问题


How can I use the following code to delete a selection from a listbox and removing it from the list the contains it also? The selections in the listbox are dictionaries which I store in a list.

.................code..............................
self.frame_verDatabase = Listbox(master, selectmode = EXTENDED)
        self.frame_verDatabase.bind("<<ListboxSelect>>", self.OnDouble)
        self.frame_verDatabase.insert(END, *Database.xoomDatabase) 
        self.frame_verDatabase.pack()

        self.frame_verDatabase.config(height = 70, width = 150)

    def OnDouble(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        print ("selection:", selection, ": '%s'" % value)

Example: When I make a selection in the listbox, this data gets returned:

selection: (2,) : '{'Fecha de Entrega': '', 'Num Tel/Cel': 'test3', 'Nombre': 'test3', 'Num Orden': '3', 'Orden Creada:': ' Tuesday, June 23, 2015', 'Email': 'test3'}'

回答1:


from tkinter import *
things = [{"dictionaryItem":"value"}, {"anotherDict":"itsValue"}, 3, "foo", ["bar", "baz"]]
root = Tk()
f = Frame(root).pack()
l = Listbox(root)
b = Button(root, text = "delete selection", command = lambda: delete(l))
b.pack()
l.pack()

for i in range(5):
    l.insert(END, things[i])

def delete(listbox):

    global things
    # Delete from Listbox
    selection = l.curselection()
    l.delete(selection[0])
    # Delete from list that provided it
    value = eval(l.get(selection[0]))
    ind = things.index(value)
    del(things[ind])
    print(things)

root.mainloop()

Edited for clarity. Since the listbox in this case only included dict objects I simply eval the value that is pulled from the listbox, get its index inside the list object, and delete it.

Everything from the second comment up to the print statement can be accomplished in one line as follows:

del(things[things.index(eval(l.get(selection[0])))])

If you feel like being creative.



来源:https://stackoverflow.com/questions/31015774/removing-a-selection-from-a-listbox-as-well-as-remove-it-from-the-list-that-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!