1
import Tkinter as tk
root = tk.Tk()`

def printer(field) :
    print field.get()

entry = tk.Entry(root)
entry.pack()
entry.bind("<Key>", lambda event : printer(entry))

root.mainloop()

Input : ABC

Output :
(empty)
A
AB

At any point of time it always outputs one less then the presently entered text in the Entry field. So, how could I repair it ?

JDoe
  • 96
  • 2
  • 10

1 Answers1

2

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.

JohanL
  • 6,671
  • 1
  • 12
  • 26