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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.