【问题标题】:Python - Return Listbox selection as a listPython - 将列表框选择作为列表返回
【发布时间】:2026-01-10 10:45:01
【问题描述】:

我遇到了几个比我的问题更复杂的问题的解决方案,所以如果这是重复的,我深表歉意,但在这种情况下我似乎无法调整其他解决方案来满足我的需求。

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

这是我目前所拥有的:

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

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

【问题讨论】:

  • 到目前为止你的代码有什么问题
  • 也许我没有访问选择列表吧?我不知道如何访问它,我需要使用列表的值创建目录。
  • 你是说 onselect 没有被调用?
  • 我相信是的,如果我在 onselect 中添加“打印选择”,它会在每次更改时打印一条显示选择的行。我需要在函数外部访问它以自动创建名称与所选值相同的目录。
  • 既然你似乎没有使用任何类结构,就使用一个全局变量

标签: python tkinter listbox


【解决方案1】:

我自己只是在学习这个主题。如果我理解正确,您希望存储并使用此列表以供将来使用。我认为将列表框定义为一个类,并将列表存储为类属性是要走的路。

以下内容来自 Programming Python,第 4 版,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()

【讨论】:

  • 它会动态更新交互窗口中的选择,因此绝对有效。谢谢 我如何访问列表?假设我需要将一个文件夹命名为与第 n 个索引相同的值?
  • @N_8_ 我尝试编写一个快速示例但失败了。简短而糟糕的答案是,我认为这取决于是否需要在接口循环运行时或在其终止后访问列表。如果是前者,并且您将 myList 的一个实例(例如“Bob”)打包到一个更大的框架中,那么 folder name = Bob.selections[n] 应该可以工作。如果不是,“鲍勃”必须在“死亡”之前传递信息,我仍在学习它是如何工作的:)也许几周后我可以给出更好的答案。
最近更新 更多