ACTION_CODES = {'-1': 'other', '0': 'delete', '1': 'insert'}
vcmd_event = namedtuple('ValidateCommandEvent',
'action index text_after text_before text_change validate reason')
class Entry(ttk.Entry):
"""Helper for ttk.Entry, particularly to validate commands"""
def __init__(self, master=None, validate='none', validatecommand=None, **kw):
# get the validate command
self._vcmd = validatecommand
# defaults validate on key if vcmd set
if self._vcmd is not None and validate == 'none':
validate = 'key'
super().__init__(master, validate=validate, **kw)
cmd = self.register(self._vcmd_impl)
cmd = (cmd, '%d', '%i', '%P', '%s', '%S', '%v', '%V') # add tk params
self['validatecommand'] = cmd
def _vcmd_impl(self, action, index, t_after, t_before, t_change, validate, reason):
ret = self._vcmd(self, vcmd_event(
ACTION_CODES[action],
int(index), # beginning of insertion/deletion
t_after, t_before, t_change, validate, reason,
))
assert ret in (True, False), 'The return value of the validation callback must be True or False\nThe validation on %s has been disabled, set validate to none|key|focus|focusin|focusout|all to re-enable it.' % self
return ret