1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
|
# Based on iwidgets2.2.0/entryfield.itk code.
import re
import string
import types
import Tkinter
import Pmw
# Possible return values of validation functions.
OK = 1
ERROR = 0
PARTIAL = -1
class EntryField(Pmw.MegaWidget):
_classBindingsDefinedFor = 0
def __init__(self, parent = None, **kw):
# Define the megawidget options.
INITOPT = Pmw.INITOPT
optiondefs = (
('command', None, None),
('errorbackground', 'pink', None),
('invalidcommand', self.bell, None),
('labelmargin', 0, INITOPT),
('labelpos', None, INITOPT),
('modifiedcommand', None, None),
('sticky', 'ew', INITOPT),
('validate', None, self._validate),
('extravalidators', {}, None),
('value', '', INITOPT),
)
self.defineoptions(kw, optiondefs)
# Initialise the base class (after defining the options).
Pmw.MegaWidget.__init__(self, parent)
# Create the components.
interior = self.interior()
self._entryFieldEntry = self.createcomponent('entry',
(), None,
Tkinter.Entry, (interior,))
self._entryFieldEntry.grid(column=2, row=2, sticky=self['sticky'])
if self['value'] != '':
self.__setEntry(self['value'])
interior.grid_columnconfigure(2, weight=1)
interior.grid_rowconfigure(2, weight=1)
self.createlabel(interior)
# Initialise instance variables.
self.normalBackground = None
self._previousText = None
# Initialise instance.
_registerEntryField(self._entryFieldEntry, self)
# Establish the special class bindings if not already done.
# Also create bindings if the Tkinter default interpreter has
# changed. Use Tkinter._default_root to create class
# bindings, so that a reference to root is created by
# bind_class rather than a reference to self, which would
# prevent object cleanup.
if EntryField._classBindingsDefinedFor != Tkinter._default_root:
tagList = self._entryFieldEntry.bindtags()
root = Tkinter._default_root
allSequences = {}
for tag in tagList:
sequences = root.bind_class(tag)
if type(sequences) is types.StringType:
# In old versions of Tkinter, bind_class returns a string
sequences = root.tk.splitlist(sequences)
for sequence in sequences:
allSequences[sequence] = None
for sequence in allSequences.keys():
root.bind_class('EntryFieldPre', sequence, _preProcess)
root.bind_class('EntryFieldPost', sequence, _postProcess)
EntryField._classBindingsDefinedFor = root
self._entryFieldEntry.bindtags(('EntryFieldPre',) +
self._entryFieldEntry.bindtags() + ('EntryFieldPost',))
self._entryFieldEntry.bind('<Return>', self._executeCommand)
# Check keywords and initialise options.
self.initialiseoptions()
def destroy(self):
_deregisterEntryField(self._entryFieldEntry)
Pmw.MegaWidget.destroy(self)
def _getValidatorFunc(self, validator, index):
# Search the extra and standard validator lists for the
# given 'validator'. If 'validator' is an alias, then
# continue the search using the alias. Make sure that
# self-referencial aliases do not cause infinite loops.
extraValidators = self['extravalidators']
traversedValidators = []
while 1:
traversedValidators.append(validator)
if extraValidators.has_key(validator):
validator = extraValidators[validator][index]
elif _standardValidators.has_key(validator):
validator = _standardValidators[validator][index]
else:
return validator
if validator in traversedValidators:
return validator
def _validate(self):
dict = {
'validator' : None,
'min' : None,
'max' : None,
'minstrict' : 1,
'maxstrict' : 1,
}
opt = self['validate']
if type(opt) is types.DictionaryType:
dict.update(opt)
else:
dict['validator'] = opt
# Look up validator maps and replace 'validator' field with
# the corresponding function.
validator = dict['validator']
valFunction = self._getValidatorFunc(validator, 0)
self._checkValidateFunction(valFunction, 'validate', validator)
dict['validator'] = valFunction
# Look up validator maps and replace 'stringtovalue' field
# with the corresponding function.
if dict.has_key('stringtovalue'):
stringtovalue = dict['stringtovalue']
strFunction = self._getValidatorFunc(stringtovalue, 1)
self._checkValidateFunction(
strFunction, 'stringtovalue', stringtovalue)
else:
strFunction = self._getValidatorFunc(validator, 1)
if strFunction == validator:
strFunction = len
dict['stringtovalue'] = strFunction
self._validationInfo = dict
args = dict.copy()
del args['validator']
del args['min']
del args['max']
del args['minstrict']
del args['maxstrict']
del args['stringtovalue']
self._validationArgs = args
self._previousText = None
if type(dict['min']) == types.StringType and strFunction is not None:
dict['min'] = apply(strFunction, (dict['min'],), args)
if type(dict['max']) == types.StringType and strFunction is not None:
dict['max'] = apply(strFunction, (dict['max'],), args)
self._checkValidity()
def _checkValidateFunction(self, function, option, validator):
# Raise an error if 'function' is not a function or None.
if function is not None and not callable(function):
extraValidators = self['extravalidators']
extra = extraValidators.keys()
extra.sort()
extra = tuple(extra)
standard = _standardValidators.keys()
standard.sort()
standard = tuple(standard)
msg = 'bad %s value "%s": must be a function or one of ' \
'the standard validators %s or extra validators %s'
raise ValueError, msg % (option, validator, standard, extra)
def _executeCommand(self, event = None):
cmd = self['command']
if callable(cmd):
if event is None:
# Return result of command for invoke() method.
return cmd()
else:
cmd()
def _preProcess(self):
self._previousText = self._entryFieldEntry.get()
self._previousICursor = self._entryFieldEntry.index('insert')
self._previousXview = self._entryFieldEntry.index('@0')
if self._entryFieldEntry.selection_present():
self._previousSel= (self._entryFieldEntry.index('sel.first'),
self._entryFieldEntry.index('sel.last'))
else:
self._previousSel = None
def _postProcess(self):
# No need to check if text has not changed.
previousText = self._previousText
if previousText == self._entryFieldEntry.get():
return self.valid()
valid = self._checkValidity()
if self.hulldestroyed():
# The invalidcommand called by _checkValidity() destroyed us.
return valid
cmd = self['modifiedcommand']
if callable(cmd) and previousText != self._entryFieldEntry.get():
cmd()
return valid
def checkentry(self):
# If there is a variable specified by the entry_textvariable
# option, checkentry() should be called after the set() method
# of the variable is called.
self._previousText = None
return self._postProcess()
def _getValidity(self):
text = self._entryFieldEntry.get()
dict = self._validationInfo
args = self._validationArgs
if dict['validator'] is not None:
status = apply(dict['validator'], (text,), args)
if status != OK:
return status
# Check for out of (min, max) range.
if dict['stringtovalue'] is not None:
min = dict['min']
max = dict['max']
if min is None and max is None:
return OK
val = apply(dict['stringtovalue'], (text,), args)
if min is not None and val < min:
if dict['minstrict']:
return ERROR
else:
return PARTIAL
if max is not None and val > max:
if dict['maxstrict']:
return ERROR
else:
return PARTIAL
return OK
def _checkValidity(self):
valid = self._getValidity()
oldValidity = valid
if valid == ERROR:
# The entry is invalid.
cmd = self['invalidcommand']
if callable(cmd):
cmd()
if self.hulldestroyed():
# The invalidcommand destroyed us.
return oldValidity
# Restore the entry to its previous value.
if self._previousText is not None:
self.__setEntry(self._previousText)
self._entryFieldEntry.icursor(self._previousICursor)
self._entryFieldEntry.xview(self._previousXview)
if self._previousSel is not None:
self._entryFieldEntry.selection_range(self._previousSel[0],
self._previousSel[1])
# Check if the saved text is valid as well.
valid = self._getValidity()
self._valid = valid
if self.hulldestroyed():
# The validator or stringtovalue commands called by
# _checkValidity() destroyed us.
return oldValidity
if valid == OK:
if self.normalBackground is not None:
self._entryFieldEntry.configure(
background = self.normalBackground)
self.normalBackground = None
else:
if self.normalBackground is None:
self.normalBackground = self._entryFieldEntry.cget('background')
self._entryFieldEntry.configure(
background = self['errorbackground'])
return oldValidity
def invoke(self):
return self._executeCommand()
def valid(self):
return self._valid == OK
def clear(self):
self.setentry('')
def __setEntry(self, text):
oldState = str(self._entryFieldEntry.cget('state'))
if oldState != 'normal':
self._entryFieldEntry.configure(state='normal')
self._entryFieldEntry.delete(0, 'end')
self._entryFieldEntry.insert(0, text)
if oldState != 'normal':
self._entryFieldEntry.configure(state=oldState)
def setentry(self, text):
self._preProcess()
self.__setEntry(text)
return self._postProcess()
def getvalue(self):
return self._entryFieldEntry.get()
def setvalue(self, text):
return self.setentry(text)
Pmw.forwardmethods(EntryField, Tkinter.Entry, '_entryFieldEntry')
# ======================================================================
# Entry field validation functions
_numericregex = re.compile('^[0-9]*$')
_alphabeticregex = re.compile('^[a-z]*$', re.IGNORECASE)
_alphanumericregex = re.compile('^[0-9a-z]*$', re.IGNORECASE)
def numericvalidator(text):
if text == '':
return PARTIAL
else:
if _numericregex.match(text) is None:
return ERROR
else:
return OK
def integervalidator(text):
if text in ('', '-', '+'):
return PARTIAL
try:
string.atol(text)
return OK
except ValueError:
return ERROR
def alphabeticvalidator(text):
if _alphabeticregex.match(text) is None:
return ERROR
else:
return OK
def alphanumericvalidator(text):
if _alphanumericregex.match(text) is None:
return ERROR
else:
return OK
def hexadecimalvalidator(text):
if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'):
return PARTIAL
try:
string.atol(text, 16)
return OK
except ValueError:
return ERROR
def realvalidator(text, separator = '.'):
if separator != '.':
if string.find(text, '.') >= 0:
return ERROR
index = string.find(text, separator)
if index >= 0:
text = text[:index] + '.' + text[index + 1:]
try:
string.atof(text)
return OK
except ValueError:
# Check if the string could be made valid by appending a digit
# eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-').
if len(text) == 0:
return PARTIAL
if text[-1] in string.digits:
return ERROR
try:
string.atof(text + '0')
return PARTIAL
except ValueError:
return ERROR
def timevalidator(text, separator = ':'):
try:
Pmw.timestringtoseconds(text, separator)
return OK
except ValueError:
if len(text) > 0 and text[0] in ('+', '-'):
text = text[1:]
if re.search('[^0-9' + separator + ']', text) is not None:
return ERROR
return PARTIAL
def datevalidator(text, format = 'ymd', separator = '/'):
try:
Pmw.datestringtojdn(text, format, separator)
return OK
except ValueError:
if re.search('[^0-9' + separator + ']', text) is not None:
return ERROR
return PARTIAL
_standardValidators = {
'numeric' : (numericvalidator, string.atol),
'integer' : (integervalidator, string.atol),
'hexadecimal' : (hexadecimalvalidator, lambda s: string.atol(s, 16)),
'real' : (realvalidator, Pmw.stringtoreal),
'alphabetic' : (alphabeticvalidator, len),
'alphanumeric' : (alphanumericvalidator, len),
'time' : (timevalidator, Pmw.timestringtoseconds),
'date' : (datevalidator, Pmw.datestringtojdn),
}
_entryCache = {}
def _registerEntryField(entry, entryField):
# Register an EntryField widget for an Entry widget
_entryCache[entry] = entryField
def _deregisterEntryField(entry):
# Deregister an Entry widget
del _entryCache[entry]
def _preProcess(event):
# Forward preprocess events for an Entry to it's EntryField
_entryCache[event.widget]._preProcess()
def _postProcess(event):
# Forward postprocess events for an Entry to it's EntryField
# The function specified by the 'command' option may have destroyed
# the megawidget in a binding earlier in bindtags, so need to check.
if _entryCache.has_key(event.widget):
_entryCache[event.widget]._postProcess()
|