How to remove blank line at end of tkinter textbox?

Viewed 463

When I run this code, it adds a blank line to the bottom of my textbox. I want my textbox to just show NEW TEXT after return is pressed, and I cannot figure out how to accomplish it. I searched on this site and could not find an answer, so apologies in advance if this is a duplicate question.

import tkinter as tk

def update(event):
    entry.delete('1.0', tk.END)
    entry.insert('1.0', 'NEW TEXT')
    if entry.get('end-1c', 'end') == '\n':
        entry.delete('end-1c', 'end')

root = tk.Tk()
root.config(bg='snow3')
root.geometry('200x200')
entry = tk.Text(root, height=1.3, width=12)
entry.bind('<Return>', update)
entry.configure(wrap='none')
entry.pack()
root.mainloop()
1 Answers

You cannot remove the final newline. That is baked into the text widget.

However, the problem is not the built-in newline. The problem is that the return key is inserting a newline after your function runs. That is because your binding happens before the built-in bindings, which is an important part of the way tkinter handles key bindings (and is a brilliant design!).

In short, this is what happens:

  • user presses the return key
  • your function is called from a widget-specific binding
  • your function deletes everything
  • your function inserts new text
  • your function returns
  • the Text widget class binding inserts a newline

To prevent that last step from happening, you need to return the string "break" from your function. That will prevent the default behavior defined by the Text widget from happening. The end result is that the changes you made to the widget in your function are the only changes made to the widget when the user presses the return key.

def update(event):
    entry.delete('1.0', tk.END)
    entry.insert('1.0', 'NEW TEXT')
    return "break"

For a slightly longer explanation of why this happens, see this answer to the question Basic query regarding bindtags in tkinter.

Related