Home > Back-end >  How do I count amount of item with same text in a listbox (Tkinter)
How do I count amount of item with same text in a listbox (Tkinter)

Time:11-11

I'm trying to get the number of items with the same text at the end like a,1 b,1 and c,1.

I cant think of anything to make it work.

from tkinter import *
root=Tk()
Listbox(root).pack()
Listbox.insert(END,'a,1','b,1','c,1')

root.mainloop()

CodePudding user response:

You can use a for loop, listbox.get(0, END) (which gets all the items in a Listbox), and str.endswith() to count the number of items that end with a certain string. Here is an example:

from tkinter import *
root=Tk()
list_box = Listbox(root)
list_box.pack()
list_box.insert(END,'a,1','b,1','c,1')

# Count the number of items that end in "a,1"
items = 0
for i in list_box.get(0, END):
    if i.endswith("a,1"):
        items  = 1

print("{} items end with 'a,1'.".format(items))

root.mainloop()
  • Related