tags:

views:

260

answers:

2

I've got a Tcl/Tk window with an entry box in which I'd like to force upper case character entry. That is, if any letters are typed I'd like them to appear in upper case in the entry field, instead of simply rejecting any lowercase input.

I've looked at the documentation for entry and the Entry Validation page on the Tcl/Tk wiki, but I must not be looking in the correct place because although there are lots of validation examples, I can't find an example of filtering key input to change the case.

The closest I've been able to get is something like the following:

entry .message -validate key -validatecommand {
    .message insert %i [string toupper "%S"]
    return 0
}

This forces the first character typed to upper case, but subsequent characters are not translated. In fact, the validate script is not called at all after the first character. If I omit the .message insert command for testing, the validate script is called for each character.

+4  A: 

If you set a new value for your entry within your validation command, validation is turned off (presumably to prevent an infinite loop). However you can turn it back on afterwards:

entry .message -validate key -validatecommand {
    .message insert %i [string toupper "%S"]
    .message configure -validate key
    return 0
}
mark4o
Note that I also had to check the type of action (`%d`) to make sure it was 1 (insert), otherwise deleting text wouldn't work.
Greg Hewgill
+1  A: 

Alternatively you can use events and bindings:

entry .message
bind .message <KeyRelease> {
    set v [string toupper [.message get]]
    .message delete 0 end
    .message insert 0 $v
    }

pack .message

This gives an idea of the type of thing you could look at doing - the processing in the event is very simple here and could be greatly improved.

Jackson