0

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!

MechaBrix
  • 15
  • 7

1 Answers1

1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thank you it's perfectly working, I'm just suprised we can pass argument or something while binding for change this and choose to run function after or before widget events... – MechaBrix May 05 '22 at 05:23