Reputation: 23
from tkinter import *
def hi(event):
print(txt.get('1.0',END))
txt.delete('1.0',END)
root = Tk()
lbl = Label(root, text="client")
lbl.pack()
txt = Text(root, height=10, width=50)
txt.pack()
txt.bind('<Return>', hi)
btn = Button(root, text="OK")
btn.pack()
root.mainloop()
When I delete Text widget contents, a blank line is left. How to prevent that?
Upvotes: 2
Views: 433
Reputation: 22784
You must ask tkinter not to propagate that event to other handlers as follows:
from tkinter import *
def hi(event):
print(txt.get('1.0',END))
txt.delete('1.0',END)
return "break"
root = Tk()
lbl = Label(root, text="client")
lbl.pack()
txt = Text(root, height=10, width=50)
txt.pack()
txt.bind('<Return>', hi)
btn = Button(root, text="OK")
btn.pack()
root.mainloop()
Upvotes: 1
Reputation: 4964
What happens is that the text widget still gets the return you entered. Binding the Enter does not inhibits the propagation of the event after your function ends, unless you alter it to cancel event propagation by returning the break string, like this:
def hi(event):
print(txt.get('1.0',END))
txt.delete('1.0',END)
return 'break'
Upvotes: 2
Reputation: 386230
The built-in bindings cause a newline to be inserted when you press the return key. When you create a binding, your bound function is called before the default behavior. Thus, when you press return, your function deletes everything, and then the default action inserts a newline.
If you want to prevent the default action from happening, your function needs to return the string break
:
def hi(event):
print(txt.get('1.0',END))
txt.delete('1.0',END)
return "break"
Upvotes: 3