Validating Entry in tkinter

Peter Otten __peter__ at web.de
Mon Jul 25 03:32:49 EDT 2011


Saul Spatz wrote:

> In tcl/tk an Entry widget can be set to validate its contents with the
> validate option.  You have to give it a validatecommand (vcmd), which is a
> tcl script that runs when some action triggers validation.  Usually, the
> script would use "percent substitutions" so the script would be something
> like {ValidInt %P} where %P is the value of the widget should the proposed
> change occur.
> 
> Can one do something like this in tkinter?  I've verified that with
> 
> e = Entry(master, validate = 'all', vcmd = validInt)
> 
> the validInt function is called, but it isn't passed any parameters. I
> can't find that e has any attribute corresponding to the %P value above.
> 
> Is it not possible to do this in tkinter, or have I overlooked something?

Some time ago I came up with 

http://mail.python.org/pipermail/python-list/2009-September/1220447.html

import Tkinter as tk

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

if __name__ == "__main__":
    root = tk.Tk()
    name = root.register(validate)
    cmd = 'expr {[%(name)s %(parms)s]}' % dict(name=name, parms="%s %P")
    var = tk.StringVar()
    entry = tk.Entry(root, textvariable=var,
                     validate="all", validatecommand=cmd)
    entry.pack()
    entry.focus_set()
    root.mainloop()





More information about the Python-list mailing list