我正在尝试围绕Tkinter列表框构建一个类,同时为它添加一些特定于应用程序的属性。我们的想法是能够调用一个通用列表框,它返回列表中所选项的索引。列表框终于有效,但现在我的返回值出现了问题:
根据文档,函数listbox.curselection()返回所选项的索引号,但它不会 - 它将所选条目作为元组返回。
是否有listbox方法返回所选项目的索引?或者我是否必须再次搜索我的列表以查找所选项目的索引?
class AudiListbox():
def __init__(self, i_root, i_list):
self.root = i_root
self.root.scrollbar = Scrollbar(self.root, orient=VERTICAL)
self.root.listbox=Listbox(self.root)
self.root.listbox.bind('<<ListboxSelect>>',self.CurSelect)
self.root.listbox.place(x=1, y=1)
self.root.scrollbar.config(command=self.root.listbox.yview)
self.root.scrollbar.pack(side=RIGHT, fill=Y)
self.root.listbox.pack(side=LEFT, fill=BOTH, expand=1)
self.root.listbox.insert(END, "------")
for items in i_list:
self.root.listbox.insert(END,items)
print items
def CurSelect(self, a):
value=self.root.listbox.curselection()
print type(value)
我很感激你的评论。
答案 0 :(得分:0)
是否有listbox的方法返回所选项的索引?
是的,它是curselection()
。它将返回一个包含每个所选项的索引的元组
如果要打印出所选内容,可以对元组中的每个项目使用get
方法:
def CurSelect(self, a):
indexes = self.root.listbox.curselection()
items = [self.root.listbox.get(index) for index in indexes]
print("indexes:", indexes)
print("items:", items)