3

OS: Windows 8.1 Python 3.5

In Tkinter

I found plenty of code to validate if an entry box is empty. But when I try to apply same method for a Text widget it does not work. It looks like the text widget has an \n character and that might be the problem.

Any idea of how to do this validation ?

1
  • Why don't you use get method? Commented Jul 23, 2016 at 8:30

2 Answers 2

10

Tkinter automatically adds a newline at the end of the data in the widget. To see if the widget is empty, compare the index right before this newline with the starting index; if they are the same, the widget is empty.

You can use the index "end-1c" (or "end - 1 char") to represent the index of the character immediately before the trailing newline. You can use the text widget's compare method to do the comparison.

if text.compare("end-1c", "==", "1.0"):
    print("the widget is empty")

Assuming you don't have hundreds of megabytes in your widget, you can also get the contents and compare the length to zero. This makes a temporary copy of the data in the widget, which in most cases should be fairly harmless. Again, you don't want to get the trailing newline:

if len(text.get("1.0", "end-1c")) == 0:
    print("the widget is empty")
Sign up to request clarification or add additional context in comments.

3 Comments

Thumbs up for the compare method. And is using get method not a good idea in this case?
@ParvizKarimli: you can use get if you want. It makes a copy of the data, so it's going to be slower and more memory intensive than the compare. In most cases, the difference in performance will not be noticeable unless you're loading hundreds or thousands of megabytes into the widget.
Yes, that's right, I know that. I just thought something was wrong with get, so @user2067030 hadn't tried it. That's why I asked. Thanks for clarifying my question.
-1

You Can Also Do Like This:

from tkinter import*
root=Tk()
def check():
    if str(t1.get(1.0,END)).isspace():
        print('The Widget Is Empty')
    else:
        print('The Widget Is Not Empty')
t1=Text(root)
t1.pack()
b1=Button(root,text='Check The Text Widget Is Empty',command=check)
b1.pack()
mainloop()

1 Comment

If the widget is filled with only whitespace (spaces, tabs, newlines) this method will incorrectly say it is empty.

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.