【问题标题】:How do I use .get to retrieve multiple selections with a Listbox in Python?如何使用 .get 在 Python 中通过列表框检索多个选择?
【发布时间】:2020-03-05 00:31:40
【问题描述】:

我正在尝试制作一个程序,其中一个功能是从 ListBox 中获取用户选择的选项并将它们显示在弹出窗口中,但我一直不知道在哪里以及如何使用 .get() .

代码如下:

        # Adds Listbox
        self.toppings_label = Label(self, text="Toppings:")
        self.toppings_label.grid(row=3, column=0)

        self.toppings_selection = Listbox(self, selectmode="multiple")
        self.toppings_selection.grid(row=3, column=1, columnspan=3)
        self.toppings_selection.insert(1, "Pepperoni")
        self.toppings_selection.insert(2, "Sausage")
        self.toppings_selection.insert(3, "Green Peppers")
        self.toppings_selection.insert(4, "Olives")
        self.toppings_selection.insert(5, "Chicken")

        …

        toppings = self.toppings_selection.get()

        mb.showinfo("Confirm", "Toppings: " + toppings)

【问题讨论】:

  • 您可以添加Button() 来运行函数(按下按钮时),该函数使用.get() 从列表框中获取选定数据。

标签: python tkinter listbox


【解决方案1】:

这是处理多项选择的方法。当然,不是打印到终端,您可以在 for 循环中添加一个附加来构建您将提交到对话框的字符串:

    selection = self.toppings_selection.curselection()
    for i in selection:
        print(self.toppings_selection.get(i))

【讨论】:

  • 我看到我关于多项选择的答案出现在我之前对单选的回答之前,这不是讨论的时间顺序,所以请注意我现在评论的代码确实解决了多项选择题。
  • 您不能期望答案以任何特定顺序出现。顺序会随着时间而变化。
  • 感谢您的意见。但是,现在我无法在没有 TclError 的情况下进行单个选择。
  • 请发布您的代码,我会看看,因为我目前正在使用它进行单选和多选,没有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 2021-06-18
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多