Home > other >  What is %P in Tcl?
What is %P in Tcl?

Time:09-17

I saw this code en Tcl:

entry .amount -validate key -validatecommand {
    expr {[string is int %P] || [string length %P]==0}
}

I know that it's an entry validation but, what does "%P" in that code? I was looking in the Tcl's doc but I didn't find nothing.

I think this is another way to do it but it has the same symbols:

proc check_the_input_only_allows_digits_only {P} {
    expr {[string is int P] || [string length P] == 0}
}
entry .amount \
    -validate key \
    -validatecommand {check_the_input_only_allows_digits_only %P}

CodePudding user response:

The tcl-tk page for entry says

%P

The value of the entry if the edit is allowed. If you are configuring the entry widget to have a new textvariable, this will be the value of that textvariable.

https://www.tcl.tk/man/tcl8.4/TkCmd/entry.html#M25

CodePudding user response:

I think this is another way to do it but it has the same symbols:

You're close. You just have to use $ in a few places because you're just running a procedure and that's as normal for using parameters to procedures.

proc check_the_input_only_allows_digits_only {P} {
    expr {[string is int $P] || [string length $P] == 0}
}
entry .amount \
    -validate key \
    -validatecommand {check_the_input_only_allows_digits_only %P}

It's recommended that you write things like that using a procedure for anything other than the most trivial of validations (or other callbacks); putting the complexity directly in the callback gets confusing quickly.

I recommend keeping validation loose during the input phase, and only making stuff strictly validated on form submission (or pressing the OK/Apply button, or whatever it is that makes sense in the GUI) precisely because it's really convenient to have invalid states there for a while in many forms while the input is being inputted. Per-key validation therefore probably should be used to only indicate whether it's believed that form submission will work, not to outright stop even transients from existing.


The string is int command returns true for zero-length input precisely because it was originally put in to work with that validation mechanism. It grinds my gears that actual validation of an integer needs string is int -strict. Can't change it now though; it's just a wrong default…

entry .amount -validate key -validatecommand {string is int %P}
  • Related