0

So suppose I have a code like this.

def test(widget):
    widget.widget.delete("1.0", tkinter.END)
t=tkinter.Tk()
b=tkinter.scrolledtext.ScrolledText()
b.bind("<Return>", test)
b.pack()
t.mainloop()

This will delete the textbox but the cursor will always be on the second line (and after that it won't go to third line for example, so it's not like every time a new line is created, it will always be at the second line).

It sounds like first this event is triggered, then the key is processed, so when the textbox is deleted, the Enter key makes a second line.

This seems to only happen with this event.

Hormoz
  • 291
  • 1
  • 2
  • 7

2 Answers2

1

Events bound to a widget are handled before the default bindings. Therefore, your code runs before tkinter inserts the newline.

If you want to prevent the default behavior, return the literal string "break" from the function.

def test(widget):
    widget.widget.delete("1.0", tkinter.END)
    return "break"

For a detailed explanation of how events are processed see this answer

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Just a bit before your answer (or around the time you answered) I found the answer myself. Thanks though! – Hormoz Jun 20 '21 at 18:53
0

Returning the string "Break" prevents python from handling the key event itself, so this fixes the problem.

Hormoz
  • 291
  • 1
  • 2
  • 7