Skip to content Skip to sidebar Skip to footer

How Can I Remove Newline Character (\n) At The End Of Text Widget?

I am working on a Tkinter GUI. I am wondering how can I remove newline character (\n) at the end of Text widget? It's making my App looking ugly I don't want this. Example code is:

Solution 1:

Your problem doesn't appear to be any extra newlines, it's simply that you configured it to show 7 lines but you're only inserting 6. If you set the height to 6 you won't see this blank line.

Solution 2:

Assert:

hist_t = tk.Text(...)

You can always call hist_t.delete('end-1c', 'end') whenever you want to remove the last char, which is newline in this case. You can also remove the last char only if it is newline:

while hist_t.get('end-1c', 'end') == '\n':
    hist_t.delete('end-1c', 'end')

Solution 3:

Textbox always inserts a blank line at the end. The problem was compounded when editing textbox and yet another blank line was inserted. However during edit you could remove blank lines so you can't use "end-1c" all the time.

The trick was to remove 1 or more extra blank lines after editing:

# Rebuild lyrics from textboxself.work_lyrics_score = \
    self.lyrics_score_box.get('1.0', tk.END)
whileself.work_lyrics_score.endswith('\n\n'):
    # Drop last blank line which textbox automatically inserts.# User may have manually deleted during edit so don't always assumeself.work_lyrics_score = self.work_lyrics_score[:-1]       

Note however this is with Linux. For Windows you might need something like:

whileself.work_lyrics_score.endswith('\n\r\n\r'):
    # Drop last blank line which textbox automatically inserts.# User may have manually deleted during edit so don't always assumeself.work_lyrics_score = self.work_lyrics_score[:-2]

Or whatever the the control code is for DOS/Windows LF/CR (Line Feed / Carriage Return) typewriter days style is.

Post a Comment for "How Can I Remove Newline Character (\n) At The End Of Text Widget?"