LAS
LAS

Reputation: 179

How to set back tkinter entry validation after deleting the content

I have these few lines of code here to validate my entry widget which works fine but after deleting the content and want to set the validation back it doesn't work .After deleting am able to type text i don't want the entry to accept.

from tkinter import *


def MoneyValidation(S):
    if S in ['0', '1', '2', '3', '4', '5']:
        return True
    root.bell()
    return False


def delete():
    vcmd_money2 = (root.register(MoneyValidation), '%S')
    e.config(invcmd="keys", vcmd=vcmd_money2)
    e.delete(0, END)
    e.delete(0, END)

    vcmd_money = (root.register(MoneyValidation), '%S')
    e.config(validate="key", vcmd=vcmd_money)




root = Tk()

vcmd_money = (root.register(MoneyValidation), '%S')
e = Entry(root, validate="key", vcmd=vcmd_money)
e.pack()

b = Button(text="DELETE", command=delete)
b.pack()

root.mainloop()

Upvotes: 2

Views: 952

Answers (2)

Kevin
Kevin

Reputation: 76254

You don't need to disable validation at all if you modify your validation rule to allow the deletion of multiple characters at once. If you type "123" and run e.delete(0, END) without disabling validation, then MoneyValidation's S value will be "123". If you validate each character of S individually, then you can permit these kinds of multi-digit changes.

from tkinter import *


def MoneyValidation(S):
    if all(c in ['0', '1', '2', '3', '4', '5'] for c in S):
        return True
    root.bell()
    return False

def delete():
    e.delete(0, END)

root = Tk()

vcmd_money = (root.register(MoneyValidation), '%S')
e = Entry(root, validate="key", vcmd=vcmd_money)
e.pack()

b = Button(text="DELETE", command=delete)
b.pack()

root.mainloop()

As an added benefit, with this approach the user can highlight part of his number and delete it with the backspace key. That wouldn't be possible if you kept MoneyValidation the way it is, and only disabled validation during the delete() call.

Upvotes: 2

fhdrsdg
fhdrsdg

Reputation: 10592

I think you're making this way harder than necessary. Simply turn off validation, delete the text and turn on validation again:

def delete():
    e.config(validate="none")
    e.delete(0, END)
    e.config(validate="key")

Upvotes: 3

Related Questions