1

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.

user3117153
  • 39
  • 1
  • 6

2 Answers2

2

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()
Community
  • 1
  • 1
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
1

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
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685