Question

This is my code:

root = Tk()

def mytest():
    var = entry.get()
    print(var)
    return True

entry = Entry(root, validate="key", validatecommand=mytest)
entry.pack()

root.mainloop()

I was trying to validate each letter that user enters.

The problem is when I use the get() method to get the current letters, I get the letters up to the previous input.

For example, assuming I am typing in the word "abc"

  • When I first typed "a", it will print nothing.
  • When I add "b", it will print "a"
  • When I continue to type "c", it will print "ab"

Why this strange behaviour?

Was it helpful?

Solution

It is not getting everything because that's exactly how the validatecommand works -- it calls a function before the text is inserted, to give you a chance to veto the insertion if the character isn't valid.

You can have Tkinter pass in the value before the change, the value if the change is accepted, the text that was inserted, and several other things to aid you in doing the validation. For an example, see this answer: https://stackoverflow.com/a/4140988/7432

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top