Binding <Key> to an Entry in Tkinter
When I bind the event <Key>
to an entry and read the content, the change somehow lags behind. I want to "dynamically update" another entry that shows the result of a calculation of the contents of various entries as soon as entry 1 is changed. But somehow the change is not recognized instantly, only the foregoing one. Don't know if the problem is clear, so let's say it like this:
If I make n changes, the changes up to n-1 are recognized. For example, if the number 1000 is in the entry and I press backspace twice, entry_1.get() would yield 100 instead of 10. 开发者_JAVA百科Hope you understand what i mean now :)
Code snippet (simplified):
self.entry_1.bind('<Key>',lambda d: self.update())
def update(self):
success=True
try:
float(self.entry_1.get())
float(self.entry_2.get())
except ValueError: success=False
if success:
self.entry_3.delete(0,"end")
x=(float(self.entry_1.get())*float(self.entry_2.get())
self.entry_3.insert("end", "%g" %x)
What might be the reason for that?
The reason is due to the order that events are processed. That order is defined by the "binding tag" (or bindtag) of the widget. By default the order is widget, class, toplevel, "all". For example, if you have a binding on the widget, and on the class, and on the toplevel window that contains the widget, and on the special case "all", the bindings will fire in that order.
I gave a lengthy writeup of this problem in this answer to the question How to bind self events in Tkinter Text widget after it will binded by Text widget?
精彩评论