2016-07-19 121 views

回答

2

可以使用get()方法從列表中選擇一個或多個項目。

在第一步中,使用get(0, END)得到名單列表中的所有項目的;在第二步驟中使用Finding the index of an item given a list containing it in Python轉發到index()方法:

import Tkinter as Tk 

master = Tk.Tk() 

listbox = Tk.Listbox(master) 
listbox.pack() 

# Insert few elements in listbox: 
for item in ["zero", "one", "two", "three", "four", "five", "six", "seven"]: 
    listbox.insert(Tk.END, item) 
# Return index of desired element to seek for 
def check_index(element): 
    try: 
     index = listbox.get(0, "end").index(element) 
     return index 
    except ValueError: 
     print'Item can not be found in the list!' 
     index = -1 # Or whatever value you want to assign to it by default 
     return index 

print check_index('three') # Will print 3 

print check_index(100) # This will print: 
        # Item can not be found in the list! 
        # -1 

Tk.mainloop() 
0

你需要得到列表框的內容,然後搜索列表:

lb = tk.Listbox(...) 
... 
try: 
    index = lb.get(0, "end").index("the thing to search for") 
except ValueError: 
    index = None 
相關問題