entry widget won't validate

Peter Otten __peter__ at web.de
Tue Sep 22 05:29:34 EDT 2009


Mike wrote:

> On Sep 21, 12:47 pm, Peter Otten <__pete... at web.de> wrote:
>> Mike wrote:
>> > I'm trying to arrange for an Entry widget to check whether its data
>> > is all digits and whether the number represented is small enough.
>> > The validate function seem to be called once at startup and not
>> > afterwards:
> 
> 
>> > The print statement run 3 times at startup.
>> > Editing an Entry does not cause any printing.
>> > Any ideas?
>>
>> Quotinghttp://www.tcl.tk/man/tcl8.5/TkCmd/entry.htm#M12:
>>
>> """
>> In general, the textVariable and validateCommand can be dangerous to mix.
>> Any problems have been overcome so that using the validateCommand will
>> not interfere with the traditional behavior of the entry widget. Using
>> the textVariable for read-only purposes will never cause problems. The
>> danger comes when you try set the textVariable to something that the
>> validateCommand would not accept, which causes validate to become none
>> (the invalidCommand will not be triggered). The same happens when an
>> error occurs evaluating the validateCommand.
>> """
>>
>> You can verify that this is indeed your problem by changing the
>> Levels.vc() method to always return True for the moment.
> 
> Returning True does seems to cause vc to be called more often.
> I'm still not getting the data I want though.
> The variable always gives me the pre-change string.
> I gather I need to do something with "%P".
> google gave me hints that I should use something called "register",
> but I'm not at all clear on what I should do with them.
> I don't know how to translate from Tcl to python.

I don't know Tcl either; the following is the first thing that seemed to 
work, after some trial and error:

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()

Peter




More information about the Python-list mailing list