Im having some trouble finding an answer to this. Is is possible to search a tk listbox for an exact entry or string and then return its location or index in the list?
Thank you.
Im having some trouble finding an answer to this. Is is possible to search a tk listbox for an exact entry or string and then return its location or index in the list?
Thank you.
You can use the get()
method to get one or more items from the list.
In a first step, use get(0, END)
to get a list of all items in the list; in a second step use Finding the index of an item given a list containing it in Python which forwards to index()
method:
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()
You need to get the contents of the listbox, then search the list:
lb = tk.Listbox(...)
...
try:
index = lb.get(0, "end").index("the thing to search for")
except ValueError:
index = None