This behavior happens because the class binding that inserts the key in the Entry is executed after the widget's binding. Therefore, when writeWhatYouGet
is executed, the Entry does not contains\ the new key yet. You can check this with the following code:
from tkinter import *
startingWindow = Tk()
entry = Entry(startingWindow)
entry.grid(row=0, column=0)
def writeWhatYouGet():
print('bind', (entry.get()).strip())
def writeWhatYouGet2():
print('bind_class', (entry.get()).strip())
entry.bind('<Key>', lambda event:writeWhatYouGet())
entry.bind_class('Entry', '<Key>', lambda event:writeWhatYouGet2(), True)
startingWindow.mainloop()
To solve this problem, you can use figbeam solution or you can use the validate command option of the Entry:
from tkinter import *
startingWindow = Tk()
def writeWhatYouGet(text):
print(text.strip())
return True
validatecmd = startingWindow.register(writeWhatYouGet)
entry = Entry(startingWindow, validate='key', validatecommand=(validatecmd, '%P'))
# %P means that the value the text will have if the change is allowed is passed to validatecmd.
entry.grid(row=0, column=0)
startingWindow.mainloop()
More details about entry validation: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html