python - 从列表框中删除选择,以及从提供它的列表中删除它

标签 python tkinter listbox python-3.4

如何使用以下代码从列表框中删除一个选择并将它从包含它的列表中删除?列表框中的选择是我存储在列表中的字典。

.................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)

例子: 当我在列表框中进行选择时,会返回以下数据:

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

最佳答案

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()

为清晰起见进行了编辑。由于本例中的 listbox 只包含 dict 对象,我只是简单地 evallistbox 中提取的值,获取其在列表对象中的索引,并将其删除。

从第二个注释到 print 语句的所有内容都可以在一行中完成,如下所示:

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

如果您想发挥创意。

关于python - 从列表框中删除选择,以及从提供它的列表中删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31015774/

相关文章:

python - 如何更改 numpy datetime64 中的年份值?

python - 如何在 Python 中从子进程向 SSH 传递命令

Python 3遇到【Decode error - output not utf-8】(sublime text 2)

javascript - 使用 jquery 从 asp 列表框中获取所选项目的数量

java - 无法从 Internet Explorer 动态 Web 表内的下拉列表中选择值

python - 交换列表中元素的更好方法?

python - 如何验证时间窗口之间是否存在重叠

python-3.x - 设置窗口图标 tkinter macosx

python - pymunk + tkinter : How to get ball to move to left or right with pymunk?

c# - 在 WPF 应用程序的列表框中列出 Azure blob