jackcf
jackcf

Reputation: 11

Getting Only The Text and Not Any of the Trailing Blank Lines from a Text Widget in Python 2.7

I'm working with Python 2.7 and tkinter.

I have a text widget that I fill with lines of text where each line is terminated with a "\n" from a file. The text in the Text widget may be modified later.

Now I want to get only the text from the Text widget and ignore any trailing blank line that may be present. The get() method will get everything to the end of the Text widget including any trailing blank lines that may be present.

How can I get the text and not the trailing blank lines?

Upvotes: 0

Views: 88

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386342

The text widget doesn't have a good way to filter out the results you get from get. You can get all but the last newline that is automatically added by tkinter by using the index end-1c, but if you have multiple blank lines at the end, the easiest way is to strip out the newlines after fetching the data:

data = the_widget.get("1.0", "end-1c").rstrip("\n")

Another way would be to use the search method going backwards from the end, with a regular expression that finds the first non-blank line. You can then get all the text up to the end of that line:

index = text.search('^.+', "end", backwards=True, regexp=True)
data = text.get("1.0", f"{index} lineend") if index else ""

Upvotes: 0

Related Questions