Matt Rogan
Matt Rogan

Reputation: 77

Python Tkinter validation command not working after deleting entry

In my program, the entry widget no longer validates after the delete command has been used on it - the idea is that if it meets a certain requirement, the text in the box is automatically deleted but continues to validate the input.

from tkinter import *

TEXT_TO_MATCH = 'APPLE'

def validate(userinput):
   if userinput == TEXT_TO_MATCH:
       print(True)
        input_box.delete(0, END)
   else:
        print(False)
   return True

window = Tk()

window.title('Delete after validation')

reg = window.register(validate)

input_box = Entry(window, validatecommand=(reg, '%P'), validate='all')
input_box.pack()

window.mainloop()

Upvotes: 0

Views: 443

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385880

The entry widget automatically resets the validate option to "none" when you edit the entry widget from within the validation function.

You can re-enable the validation by using after_idle to reset the validate option after control has been returned to mainloop

def validate(userinput):
    if userinput == TEXT_TO_MATCH:
        input_box.delete(0, END)
        input_box.after_idle(lambda: input_box.configure(validate="all"))
    return True

Upvotes: 3

Related Questions