0

Sorry, if this is a duplicate or obvious question. So I simply wrote this:

import tkinter as tk
root = tk.Tk()


def on_key_pressed(e: tk.Event):
    print(text_field.get())


text_field = tk.Entry()
text_field.pack()
text_field.bind("<KeyPress>", on_key_pressed)

When I press key, it outputs like a previous typed string and not considering the key that has just been pressed. I guess maybe this is because the event keyPress happens too fast, and Entry didn't register this new change yet.

Am I right, or what will be a better explanation of this?

Danya K
  • 165
  • 1
  • 10

1 Answers1

0

The short answer is that your binding happens before the default binding, and it's the default binding that causes the character to be entered into the widget.

See Basic query regarding bindtags in tkinter for more information

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thank you! So, if I rebind tags, so that first tag will be a class and than a widget itself, it will show correctly. So just add something like this: `text_field.bindtags(('Entry', '.!entry', '.', 'all'))` – Danya K Jul 19 '23 at 17:52
  • @DanyaK: that means that bindings on the widget can't override the default bindings, but if you don't need to do any overriding, that would work. – Bryan Oakley Jul 19 '23 at 18:14
  • oh, l see. I think I will need to do overriding. Is there are a way to do an exception for a set or get functions of Entry in bindtags? Or what should I use instead? – Danya K Jul 19 '23 at 19:20
  • Or does the third example from your link creates what I needed? So just a new tag could be created after Entry class tag and it binds to the function? Will I be able to do overriding? – Danya K Jul 19 '23 at 19:57
  • @DanyaK: without knowing the actual problem you're trying to solve, it's difficult to answer your question. Your question should explain why you need to call `get()` on a keypress. Are you doing validation? Are you taking the character and passing it to some other device? Something else? – Bryan Oakley Jul 19 '23 at 20:15
  • I am still trying to make an expandable Entry widget, so that it will always match the text until some width(my previous questions with a downvote). In order to do that, I at least need to know the text in Entry just after the person typed something. I have descovered, that if Entry width set to 0 or less it will start to become expandable without any manipulations. But still need to think, how to set "up" and "down" limits. Probably will need to know the current text – Danya K Jul 19 '23 at 22:20