Question

Consider the following code:

text = Entry(); text.pack()
def show(e):
    print text.get()
text.bind('<Key>', show)

Let's say I put the letters ABC in the Entry, one by one. The output would be:

>>> 
>>> A
>>> AB

Note that when pressing A, it prints an empty string. When I press B, it prints A, not AB. If i don't press anything after C, it will never be shown. It seems that the Entry content is only updated after the binded command has returned, so I can't use the actual Entry value in that function.

Is there any way to get an updated Entry value to use inside a binded command?

Was it helpful?

Solution

You could replace the <Key> event with the <KeyRelease> event. That should work.

Here is a list of events: http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html#event-types

OTHER TIPS

The reason for this has to do with Tk "bindtags". Bindings are associated with tags, and the bindings are processed in tag order. Both widget names and widget classes are tags, and they are processed in that order (widget-specific bindings first, class bindings second).

For that reason, any time you press a key your widget specific binding will fire before the class binding has a chance to modify the widget.

There are many workarounds. The simplest is to bind to <KeyRelease> since the class bindings happen on the key press. There are other solutions that involve either adding or rearranging bind tags, or using the built-in data validation features of the entry widget. Which is best depends on what you're really trying to accomplish.

For more information on the data validation functions, see this question: Interactively validating Entry widget content in tkinter

For a more comprehensive answer, see Tkinter: set StringVar after <Key> event, including the key pressed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top