In TCL how can I restrict the number of input characters in an entry
widget?
I have a TCL field in which a user can enter some text, I wish to restrict the length of the text (e.g. not more than 30 characters).
Are there any options for it?
In TCL how can I restrict the number of input characters in an entry
widget?
I have a TCL field in which a user can enter some text, I wish to restrict the length of the text (e.g. not more than 30 characters).
Are there any options for it?
The entry validation callback is the way, and the %P
substitution is the key. From the docs:
%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.
This means we do just this:
pack [entry .e -width 50 -validate all -validatecommand {
expr {[string length %P] <= 30}
}]
There you go, you will be unable to do any edit to the widget which makes its length go over 30. (It might be best to also add an -invalidcommand
specification so that the user can find out what happened.)
I don't think there is one, but you can use validation on the entry widget as follows:
package require Tk
pack [entry .e -validate all -validatecommand {max_length %s 30 %d}]
proc max_length {val max act} {
if {[string length $val] >= $max && $act == 1} {
return 0
}
return 1
}
The entry box will try to validate each entry, and passes the current string %s
and the action %d
to the proc
named max_length
Within this proc, the length and action is checked for. If the length is above 30 and the action is 1
(meaning an insertion), then the proc will return 0 thus stopping any more insertion.