2

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!

1

2 Answers 2

4

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")
Sign up to request clarification or add additional context in comments.

2 Comments

I do not know why someone downvoted this answer, but I can assure you it is factually correct.
@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.
-1

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

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.
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.