Validating Entry in tkinter

Peter Otten __peter__ at web.de
Mon Jul 25 08:31:13 EDT 2011


Saul Spatz wrote:

> That doesn't work, I'm being stupid,  The user might type anywhere in the
> string, not just at the end.  I need
> 
> return all([c in '1234567890abcdefABCDEF ' for c in after])

Ah, you found out already. Here's what I've come up with in the meantime.
I also changed the command to a tuple as in the example pointed out by 
Wolfgang.

import tkinter as tk

def is_valid_fromhex(s):
    for pad in "", "0":
        try:
            bytes.fromhex(s + pad)
        except ValueError:
            pass
        else:
            return True
    return False

def validate(before, after):
    print(before, "-->", after)
    return is_valid_fromhex(after)

if __name__ == "__main__":
    root = tk.Tk()
    cmd = (root.register(validate), "%s", "%P")
    entry = tk.Entry(root, validate="all", validatecommand=cmd)
    entry.pack()
    entry.focus_set()
    root.mainloop()




More information about the Python-list mailing list