[Tkinter-discuss] StringVar() .trace(), .trace_vdelete() use

Michael Lange klappnase at web.de
Thu Mar 7 10:01:16 CET 2013


Hi,

On Wed, 6 Mar 2013 20:11:39 -0700
Bob Greschke <bob at greschke.com> wrote:

> I saw that earlier in the day (and a couple of weeks ago too).  I
> understand it just about as well as lambdas. :)  Do all of those values
> get passed each time a key is pressed?  

Yes, when you register a function as validation callback, all the
registered values will be passed each time a validation occurs (which may
be every key press when validate='key', focus in/out events if
validate='focus(in/out)' or all of these if validate='all' .

> Also, each Entry() field has a
> different max length.  Where do I pass that in all of this?  It would
> need to be an arg to vcmd in the Entry().

This sounds like a job for a custom entry class. I wrote a
quick example to illustrate the usage of the Entry's vcmd that might be a
starting point for you:

#######################################################################
from Tkinter import *

class VEntry(Entry):
    def __init__(self, master=None, maxlength=5, value='foo', **kw):
        Entry.__init__(self, master, **kw)

        self._maxlength = maxlength
        self.insert('end', value)
        vcmd = (self.register(self._vcmd), '%s', '%P')
        self.configure(vcmd=vcmd, validate='all')

    def _vcmd(self, old, new):
        print old, new
        if len(new) > self._maxlength:
            return False
        return True

root = Tk()
e = VEntry(root, maxlength=7, value='bar')
e.pack(padx=100, pady=100)
e.focus_set()
root.mainloop()
#######################################################################

You see, the `%s' ("old value") parameter in this example is not really
needed, I added it just to illustrate how to pass multiple arguments to
the vcmd. See http://www.tcl.tk/man/tcl8.4/TkCmd/entry.htm#M16 for a list
of all possible percent substitutions and their meanings.
You could also try if validate='key' is sufficient for your needs.

The one thing one has to be very careful to keep in mind when writing a
validation command callback is that it must always return a boolean value
in any case, otherwise Tk will be "confused" and simply and silently turn
off validation altogether. This may especially easily happen when the vcmd
callback happens to throw an error, so one has to take care that all
possible exceptions are properly caught by try...except statements.


Regards

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

Compassion -- that's the one things no machine ever had.  Maybe it's
the one thing that keeps men ahead of them.
		-- McCoy, "The Ultimate Computer", stardate 4731.3


More information about the Tkinter-discuss mailing list