I was bored this afternoon and decided to implement a speed typing test in Python; in order to allow it to check the current word after each character I used widgetName.bind("<Key>", functionName)
on my entry widget in order to call the function whenever any key is pressed within the entry widget.
This works fine and the function is called upon each keypress, my problem occured however when I used widgetName.get()
to collect the string from the entry widget; the .get()
did not collect the contents of the widget, only those in the widget prior to the function being called.
For example, if I typed 'P' into the entry widget, my function would print 'A key was pressed', however it would only print a blank line to the console. When I continued by pressing 'y', the string 'P' was outputted to the console, upon the third keypress 'Py' was outputted and so forth.
This led me to believe that the contents of the Tkinter widget had not been updated because the .bind()
call happened before the widget contents updated, and therefore the contents of the widget were one keypress behind.
I need to know if there is a way around this, I did some research and found that I can called root.update()
or widget.update()
from within the function, which should force the UI to refresh. However this did not help and I am still faced with the same problem.
My code is as follows
root = Tk()
def keyPress(forSomeReasonThisArgumentFixesABug): ##Argument is because bind passes the event to the function
entryBox.update()
entry, word = entryBox.get(), wordBox.get()
print(entry)
wordBox = Entry(root)
wordBox.grid(row=0, column=0)
entryBox = Entry(root)
entryBox.grid(row=1, column=0)
entryBox.bind("<Key>", keyPress)
Could someone please explain how I can pass the contents of the widget to a function (Through an argument or within the function using .get() ) upon each keypress.
Thanks in advance
Edit: I have also tried using the function called by .bind()
to call another function, which looks disgusting and still doesn't work