如何从一个tkinter “多选” Listbox 获取所有内容?

huangapple go评论80阅读模式
英文:

How do you get all the contents from a tkinter "multiple select" Listbox?

问题

你可以在这里看到,我正在创建一个tkinter的ListBox并向其中填充3个项目。我只需要能够记录用户在按下按钮时选择了什么!

我知道当你点击按钮时,**bigListbox.curselection()**可以正确获取项目的索引并将它们插入到show标签中。

但是我需要实际收集当前选定的字符串,并在点击"Send"按钮时保存到文件中。

def showSelected():
    show.config(text=bigListbox.curselection())

bigListbox = Listbox(rootWindow, selectmode="multiple")
bigListbox.pack()

# 从文件加载工作站
bigArr=["MYHSS", "MY", "MORE", "Aloysius"]

myIndex = len(bigArr)

for index in range(0, myIndex):
    bigListbox.insert(myIndex, bigArr[index])

Button(rootWindow, text='Send', command=showSelected).pack(pady=20)

show = Label(rootWindow)
show.pack()
英文:

You can see here that I am creating a tkinter ListBox and populating it with 3 items. All I need to do is be able to record what the user has selected when they press the button!

I know that when you click the Button, bigListbox.curselection() gets the indexes of the items correctly and inserts them into the show label.

But I need to actually collect the currently selected strings and save them to a file upon clicking send.

def showSelected():
    show.config(text=bigListbox.curselection())


bigListbox = Listbox(rootWindow, selectmode="multiple")
bigListbox.pack()



# Load workstations from file
bigArr=["MYHSS", "MY", "MORE", "Aloysius"]

myIndex = len(bigArr)

for index in range(0, myIndex):
    bigListbox.insert(myIndex, bigArr[index])


Button(rootWindow, text='Send', command=showSelected).pack(pady=20)


show = Label(rootWindow)
show.pack()

答案1

得分: 3

你可以使用Listbox.get()方法来获取指定索引处的字符串:

def showSelected():
    # 创建一个由所选项目组成的逗号分隔列表
    items = ", ".join(bigListbox.get(idx) for idx in bigListbox.curselection())
    show.config(text=items)
英文:

You can use .get() of Listbox to get the string at specified index:

def showSelected():
    # create a comma separated list of selected items
    items = ", ".join(bigListbox.get(idx) for idx in bigListbox.curselection())
    show.config(text=items)

huangapple
  • 本文由 发表于 2023年2月16日 07:05:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定