2016-04-21 39 views
-1

我遇到了几个解决方案比我有更复杂的问题,所以我很抱歉,如果这是一个重复,但我似乎无法适应其他解决方案,以满足我的需要实例。蟒蛇 - 返回列表框选择作为列表

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

这是我到目前为止有:

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

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

+0

到目前为止你的代码有什么问题 – Natecat

+0

也许我没有正确地访问选择列表? 我无法弄清楚如何访问它,我需要使用列表的值创建目录。 –

+0

你是说onselect没有被调用? – Natecat

回答

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

它在交互式窗口中动态更新选择,所以一定可行。谢谢 虽然如何访问列表? 说我需要命名一个文件夹与第n个索引相同的值? –

+0

@ N_8_我试图编写一个简单的例子,但失败了。简而不佳的回答是我认为这取决于列表是否需要在接口循环运行时或终止后访问。如果前者和你将myList的一个实例(例如“Bob”)打包到一个更大的框架中,那么'folder name = Bob.selections [n]'应该可以工作。如果没有,“鲍勃”必须在它“死亡”之前传递信息,而且我仍然在学习如何工作:)也许在几个星期内我可以给出更好的答案。 –