Python - 将列表框选择作为列表返回

时间:2016-04-21 00:21:56

标签: python tkinter listbox

我遇到了一些比我更复杂的问题的解决方案,所以如果这是一个重复,我会道歉但在这种情况下我似乎无法根据我的需要调整其他解决方案。

我需要显示一个填充的列表框,并使用多种选择方法将选择作为一个列表返回,我可以在以后拆分和操作。

这是我到目前为止所拥有的:

from Tkinter import *

def onselect(evt):
    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
    selection = [w.get(int(i)) for i in w.curselection()]
    return selection

master = Tk()

listbox = Listbox(master,selectmode=MULTIPLE)

listbox.pack()

for item in ["one", "two", "three", "four"]:
    listbox.insert(END, item)

listbox.bind('<<ListboxSelect>>', onselect)

mainloop()

如何将选择变量正确存储为列表?

1 个答案:

答案 0 :(得分:0)

我自己就是在学习这个话题。如果我理解正确,您希望存储并使用此列表以供将来使用。我认为将列表框定义为类,并将列表存储为类属性是可行的方法。

以下借鉴Programming Python,4th ed,Ch。 9.将来的列表可以根据需要作为myList.selections访问。

from tkinter import *


class myList(Frame):
    def __init__(self, options, parent=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        self.makeWidgets(options)
        self.selections = []

    def onselect(self, event):
        selections = self.listbox.curselection()
        selections = [int(x) for x in selections]
        self.selections = [options[x] for x in selections]
        print(self.selections)

    def makeWidgets(self, options):
        listbox = Listbox(self, selectmode=MULTIPLE)
        listbox.pack()
        for item in options:
            listbox.insert(END, item)
        listbox.bind('<<ListboxSelect>>', self.onselect)
        self.listbox = listbox


if __name__ == '__main__':
    options = ["one", "two", "three", "four"]
    myList(options).mainloop()