Search code examples
tcltk-toolkitgtkentry

Restrict the number of input characters in Tk entry widget


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?


Solution

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