[Tkinter-discuss] tkinter Entry validation: insert instead of replace

Michael Lange klappnase at web.de
Fri Feb 22 15:44:34 CET 2013


Hi,

On Fri, 22 Feb 2013 01:50:45 -0800 (PST)
lansman <codelans at gmail.com> wrote:

> Anybody know why it happens?

this is a common issue. To illustrate what's going on, I changed your
validate callback a little into:

    def _validate(self, d, i, P, s, S, v, V, W):
        print '"%s"' % P,  P.isdigit()
        return P.isdigit()

then I ran the program and got:

$ python test8.py
"111" True # -> program start
"111" True # -> selected the 111 with the mouse
"" False # -> pressed the 9 key
"9111" True 

So we see, what happens is that when the selected "111" is overwritten
with "9" the Entry is *emptied first*, the empty string validates to
False and is therefore not accepted by the widget and so the 111 remains
in the widget when the 9 is inserted.

So the trick here is to let the widget accept the empty string, as in:

    def _validate(self, d, i, P, s, S, v, V, W):
        if P == '':
            return True
        return P.isdigit()

Regards

Michael

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

Lots of people drink from the wrong bottle sometimes.
		-- Edith Keeler, "The City on the Edge of Forever",
		   stardate unknown


More information about the Tkinter-discuss mailing list