Can anyone help me determine why the print statements seem to lag behind the input for this code? If you run this short program and type 1,2,3,4,5 into the input entry widget, the event triggering the method gets the current value of the typed_string Stringvar, but it lags 1 behind the input. Can someone explain why? Better yet, does anyone know of a way that any keypress to an entry widget that produces text will call the displayed value of the input variable? Current version of python is 3.8
import tkinter
from tkinter import *
class UI():
def __init__(self, master):
self.typed_string = StringVar()
self.typed_string.set("")
self.new_entry = tkinter.Entry(master, textvariable=self.typed_string)
self.new_entry.pack()
self.new_entry.bind("<Key>",self.check_string)
def check_string(self, event):
retrieved_string = self.typed_string.get()
print(retrieved_string, " was retrieved string")
print(self.new_entry.get(), " was get for entry widget")
def main():
root = Tk()
new_ui = UI(root)
root.mainloop()
if __name__ == '__main__':
main()
If you replace:
self.new_entry.bind("<Key>",self.check_string)
with
self.new_entry.bind("<KeyRelease>",self.check_string)
it does what I think you want it to do.
Reason: The Key event is triggered before the character of that key is added to the StringVar variable; or perhaps more accurately, before the key press is processed, one result of which is to add the character of the key to the variable if it is a normal printable key. The KeyRelease event is triggered after the keypress is processed and therefore after the character has already been added to the variable when you try to print it.