-1

i used .bind on a Text widget to delete all content when pressing the Return key, but the cursor wont reset to its starting position.

the code is as follows:

def send_message(event=None):
    msg = msg_bar.get(1.0, tk.END)
    print(tk.END)
    msg_bar.delete(1.0, tk.END) 

msg_bar = tk.Text(msg_frame) 
msg_bar.bind('<Return>', send_message)

i even tried using msg = msg.strip('\n') to no avail.

does tk.END ignore \n? if so how can i make sure the cursor is set correctly to the starting position?

1 Answers1

2

Your binding happens before the default behavior of inserting a newline. You delete all of the characters, your function returns, and then the default behavior of tkinter will insert a newline.

You want to prevent the default behavior in this case, so your function needs to return the string "break":

def send_message(event=None):
    msg = msg_bar.get(1.0, tk.END)
    print(tk.END)
    msg_bar.delete(1.0, tk.END) 
    return "break"
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685