是否可以搜索列表框并返回索引位置?

时间:2016-07-19 12:54:43

标签: tkinter

我在寻找答案时遇到了一些麻烦。是否可以在tk列表框中搜索确切的条目或字符串,然后在列表中返回其位置或索引?

谢谢。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您需要获取列表框的内容,然后搜索列表:

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