Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation function prints previous input and not the current one

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?

like image 463
Chris Aung Avatar asked Nov 29 '25 12:11

Chris Aung


1 Answers

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

like image 119
Bryan Oakley Avatar answered Dec 01 '25 01:12

Bryan Oakley