Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter - check if Text widget is empty

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 ?

like image 659
user2067030 Avatar asked Feb 27 '26 16:02

user2067030


1 Answers

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")
like image 88
Bryan Oakley Avatar answered Mar 02 '26 06:03

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!