Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 877
Jakob Avatar asked Aug 29 '11 13:08

Jakob


People also ask

How do you bind a key in Python?

Practical Data Science using Python Tkinter provides a way to bind the widget to perform certain operations. These operations are defined in a function that can be called by a particular widget. The bind(<button>, function()) method is used to bind the keyboard key to handle such operations.

What is Bind method in Tkinter?

In Tkinter, bind is defined as a Tkinter function for binding events which may occur by initiating the code written in the program and to handle such events occurring in the program are handled by the binding function where Python provides a binding function known as bind() where it can bind any Python methods and ...

What is bind () in Python?

The bind() method of Python's socket class assigns an IP address and a port number to a socket instance. The bind() method is used when a socket needs to be made a server socket.


1 Answers

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?

like image 129
Bryan Oakley Avatar answered Sep 21 '22 23:09

Bryan Oakley