I'm trying to execute function after pressing key. Problem is if I use this code:
text = tk.Text(root)
text.bind("<KeyPress>", lambda event:print(text.get(1.0, tk.END)))
text.pack()
When I press first key, nothing is printed. It executes my functions before inserting character, how I can avoid that ? Whitout using <KeyRelease>
Thanks!
CodePudding user response:
A simple technique is to run your code with after_idle
, which means it runs when mainloop
has processed all pending events.
Here's an example:
import tkinter as tk
def do_something():
print(text.get("1.0", "end-1c"))
root = tk.Tk()
text = tk.Text(root)
text.bind("<KeyPress>", lambda event: root.after_idle(do_something))
text.pack()
root.mainloop()
For a deeper explanation of why your binding seems to lag behind what you type by one character see this answer to the question Basic query regarding bindtags in tkinter. The question asks about an Entry
widget but the binding mechanism is the same for all widgets.