2

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?

ani627
  • 5,578
  • 8
  • 39
  • 45

2 Answers2

4

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

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
2

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.

Jerry
  • 70,495
  • 13
  • 100
  • 144
  • What if the user clicks on the first character and then types when there are already 30 characters? What if they paste 40 characters at position 29? – Bryan Oakley Oct 10 '14 at 12:45
  • 1
    @1336087 Thanks! Lol, I guess I over-thought about it. Never used `%P` before, so thanks for your question; I learned something new too :) – Jerry Oct 10 '14 at 16:11