2016-03-05 94 views
0

我想建立一個圍繞Tkinter列表框的類,同時向它添加一些應用程序特定的屬性。這個想法是能夠調用一個通用列表框,它返回列表中選定項目的索引。 Listbox終於可以工作了,但是現在我的返回值有問題了:Python Tkinter - Listbox自定義類返回索引,但沒有索引

根據文檔,函數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)