I guess the reason is that the callback comes before the entry text. However, since the key pressed is passed as an event, it would be possible to add that information manually to the printed string. However, that requires the program to handle special characters as backspace or newline.
Another solution, or rather workaround, - the one I prefer - is to define a StringVar
and connect that to the Entry
object. The StringVar
has a trace
callback, which allows us to track updates to the value. Thus, the trace callback will not happen until the new value is available. This can be implemented as:
import Tkinter as tk
root = tk.Tk()
def printer(name, index, mode):
print field_text.get()
field_text = tk.StringVar()
field_text.set('')
field_text.trace("w", printer)
entry = tk.Entry(root, textvariable=field_text)
entry.pack()
root.mainloop()
Thus, here we read the field_text
value, rather than the entry
value, but they should always be equal.