I am using Python Tkinter and I need to know if a listbox is empty or not, but I dont´t the syntax to do that. Please help me!
2 Answers
The listbox has a size method that returns a count of the number of items in the listbox:
size = the_listbox.size()
The string "end" is a special lisbox index that refers to the position after the last item in the listbox. Another solution is to get the index of "end". If it's zero, the listbox is empty.
end_index = the_listbox.index("end")
if end_index == 0:
print("the listbox is empty")
2 Comments
Bryan Oakley
I do not know why someone downvoted this answer, but I can assure you it is factually correct.
LetzerWille
@Brayn Oakley Yes, both of your hints worked for me. I am using python 3.9 on Windows 10. I prefer using .index("end") version, since .index never let me down.
Simply check if the first line is empty:
if not listbox.get(0):
print('Empty')
else:
print('Not empty')
or if other lines may be non empty, check the whole content:
if not listbox.get(0,END):
print('Empty')
else:
print('Not empty')
2 Comments
Bryan Oakley
it's possible for the listbox to not be empty but
listbox.get(0) can return an empty string, so your first method is unreliable.sciroccorics
@BryanOakley: Of course, that's why I mentioned the two options. If you know that your interface only puts non empty strings in the Listbox (which is a very common case, as listboxes are mainly used to display list of alternatives), the first method is save. But testing size() as you added in your edited post, is a nice solution