2016-07-19 83 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 
相关问题