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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
|
.. wxPython Phoenix documentation
This file was generated by Phoenix's sphinx generator and associated
tools, do not edit by hand.
Copyright: (c) 2011-2018 by Total Control Software
License: wxWindows License
.. include:: headings.inc
.. module:: wx.lib.masked.maskededit
.. currentmodule:: wx.lib.masked.maskededit
.. highlight:: python
.. _wx.lib.masked.maskededit:
==========================================================================================================================================
|phoenix_title| **wx.lib.masked.maskededit**
==========================================================================================================================================
\
contains MaskedEditMixin class that drives all the other masked controls.
====================
Masked Edit Overview
====================
masked.TextCtrl:
is a sublassed text control that can carefully control the user's input
based on a mask string you provide.
General usage example::
control = masked.TextCtrl( win, -1, '', mask = '(###) ###-####')
The example above will create a text control that allows only numbers to be
entered and then only in the positions indicated in the mask by the # sign.
masked.ComboBox:
is a similar subclass of wxComboBox that allows the same sort of masking,
but also can do auto-complete of values, and can require the value typed
to be in the list of choices to be colored appropriately.
masked.Ctrl:
is actually a factory function for several types of masked edit controls:
================= ==================================================
masked.TextCtrl standard masked edit text box
masked.ComboBox adds combobox capabilities
masked.IpAddrCtrl adds special semantics for IP address entry
masked.TimeCtrl special subclass handling lots of types as values
masked.NumCtrl special subclass handling numeric values
================= ==================================================
It works by looking for a *controlType* parameter in the keyword
arguments of the control, to determine what kind of instance to return.
If not specified as a keyword argument, the default control type returned
will be masked.TextCtrl.
Each of the above classes has its own set of arguments, but masked.Ctrl
provides a single "unified" interface for masked controls.
What follows is a description of how to configure the generic masked.TextCtrl
and masked.ComboBox; masked.NumCtrl and masked.TimeCtrl have their own demo
pages and interface descriptions.
=========================
Initialization Parameters
-------------------------
mask
Allowed mask characters and function:
========= ==========================================================
Character Function
========= ==========================================================
# Allow numeric only (0-9)
N Allow letters and numbers (0-9)
A Allow uppercase letters only
a Allow lowercase letters only
C Allow any letter, upper or lower
X Allow string.letters, string.punctuation, string.digits
& Allow string.punctuation only (doesn't include all unicode symbols)
\* Allow any visible character
| explicit field boundary (takes no space in the control; allows mix
of adjacent mask characters to be treated as separate fields,
eg: '&|###' means "field 0 = '&', field 1 = '###'", but there's
no fixed characters in between.
========= ==========================================================
These controls define these sets of characters using string.letters,
string.uppercase, etc. These sets are affected by the system locale
setting, so in order to have the masked controls accept characters
that are specific to your users' language, your application should
set the locale.
For example, to allow international characters to be used in the
above masks, you can place the following in your code as part of
your application's initialization code::
import locale
locale.setlocale(locale.LC_ALL, '')
The controls now also support (by popular demand) all "visible" characters,
by use of the * mask character, including unicode characters above
the standard ANSI keycode range.
Note: As string.punctuation doesn't typically include all unicode
symbols, you will have to use includechars to get some of these into
otherwise restricted positions in your control, such as those specified
with &.
Using these mask characters, a variety of template masks can be built. See
the demo for some other common examples include date+time, social security
number, etc. If any of these characters are needed as template rather
than mask characters, they can be escaped with \, ie. \N means "literal N".
(use \\ for literal backslash, as in: r'CCC\\NNN'.)
.. note::
Masks containing only # characters and one optional decimal point
character are handled specially, as "numeric" controls. Such
controls have special handling for typing the '-' key, handling
the "decimal point" character as truncating the integer portion,
optionally allowing grouping characters and so forth.
There are several parameters and format codes that only make sense
when combined with such masks, eg. groupChar, decimalChar, and so
forth (see below). These allow you to construct reasonable
numeric entry controls.
.. note::
Changing the mask for a control deletes any previous field classes
(and any associated validation or formatting constraints) for them.
useFixedWidthFont
By default, masked edit controls use a fixed width font, so that
the mask characters are fixed within the control, regardless of
subsequent modifications to the value. Set to ``False`` if having
the control font be the same as other controls is required. (This is
a control-level parameter.)
.. versionchanged:: 2.9.5
The default is changed to ``False`` for numctrl only
defaultEncoding
(Applies to unicode systems only) By default, the default unicode encoding
used is latin1, or iso-8859-1. If necessary, you can set this control-level
parameter to govern the codec used to decode your keyboard inputs.
(This is a control-level parameter.)
formatcodes
These other properties can be passed to the class when instantiating it:
Formatcodes are specified as a string of single character formatting
codes that modify behavior of the control::
_ Allow spaces
! Force upper
^ Force lower
R Right-align field(s)
r Right-insert in field(s) (implies R)
< Stay in field until explicit navigation out of it
> Allow insert/delete within partially filled fields (as
opposed to the default "overwrite" mode for fixed-width
masked edit controls.) This allows single-field controls
or each field within a multi-field control to optionally
behave more like standard text controls.
(See EMAIL or phone number autoformat examples.)
*Note: This also governs whether backspace/delete operations
shift contents of field to right of cursor, or just blank the
erased section.
Also, when combined with 'r', this indicates that the field
or control allows right insert anywhere within the current
non-empty value in the field. (Otherwise right-insert behavior
is only performed to when the entire right-insertable field is
selected or the cursor is at the right edge of the field.*
, Allow grouping character in integer fields of numeric controls
and auto-group/regroup digits (if the result fits) when leaving
such a field. (If specified, .SetValue() will attempt to
auto-group as well.)
',' is also the default grouping character. To change the
grouping character and/or decimal character, use the groupChar
and decimalChar parameters, respectively.
Note: typing the "decimal point" character in such fields will
clip the value to that left of the cursor for integer
fields of controls with "integer" or "floating point" masks.
If the ',' format code is specified, this will also cause the
resulting digits to be regrouped properly, using the current
grouping character.
- Prepend and reserve leading space for sign to mask and allow
signed values (negative #s shown in red by default.) Can be
used with argument useParensForNegatives (see below.)
0 integer fields get leading zeros
D Date[/time] field
T Time field
F Auto-Fit: the control calulates its size from
the length of the template mask
V validate entered chars against validRegex before allowing them
to be entered vs. being allowed by basic mask and then having
the resulting value just colored as invalid.
(See USSTATE autoformat demo for how this can be used.)
S select entire field when navigating to new field
fillChar
defaultValue
These controls have two options for the initial state of the control.
If a blank control with just the non-editable characters showing
is desired, simply leave the constructor variable fillChar as its
default (' '). If you want some other character there, simply
change the fillChar to that value. Note: changing the control's fillChar
will implicitly reset all of the fields' fillChars to this value.
If you need different default characters in each mask position,
you can specify a defaultValue parameter in the constructor, or
set them for each field individually.
This value must satisfy the non-editable characters of the mask,
but need not conform to the replaceable characters.
groupChar
decimalChar
These parameters govern what character is used to group numbers
and is used to indicate the decimal point for numeric format controls.
The default groupChar is ',', the default decimalChar is '.'
By changing these, you can customize the presentation of numbers
for your location.
Eg::
formatcodes = ',', groupChar='\'' allows 12'345.34
formatcodes = ',', groupChar='.', decimalChar=',' allows 12.345,34
(These are control-level parameters.)
shiftDecimalChar
The default "shiftDecimalChar" (used for "backwards-tabbing" until
shift-tab is fixed in wxPython) is '>' (for QUERTY keyboards.) for
other keyboards, you may want to customize this, eg '?' for shift ',' on
AZERTY keyboards, ':' or ';' for other European keyboards, etc.
(This is a control-level parameter.)
useParensForNegatives=False
This option can be used with signed numeric format controls to
indicate signs via () rather than '-'.
(This is a control-level parameter.)
autoSelect=False
This option can be used to have a field or the control try to
auto-complete on each keystroke if choices have been specified.
autoCompleteKeycodes=[]
By default, DownArrow, PageUp and PageDown will auto-complete a
partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp
and PageDown will also auto-complete, but if the field already
contains a matched value, these keys will cycle through the list
of choices forward or backward as appropriate. Shift-Up and
Shift-Down also take you to the next/previous field after any
auto-complete action.
Additional auto-complete keys can be specified via this parameter.
Any keys so specified will act like PageDown.
(This is a control-level parameter.)
Validating User Input
=====================
There are a variety of initialization parameters that are used to validate
user input. These parameters can apply to the control as a whole, and/or
to individual fields:
======================== ==================================================================
excludeChars A string of characters to exclude even if otherwise allowed
includeChars A string of characters to allow even if otherwise disallowed
validRegex Use a regular expression to validate the contents of the text box
validRange Pass a rangeas list (low,high) to limit numeric fields/values
choices A list of strings that are allowed choices for the control.
choiceRequired value must be member of choices list
compareNoCase Perform case-insensitive matching when validating against list. *Note: for masked.ComboBox, this defaults to True.*
emptyInvalid Boolean indicating whether an empty value should be considered invalid
validFunc A function to call of the form: bool = func(candidate_value) which will return ``True`` if the candidate_value satisfies some external criteria for the control in addition to the the other validation, or ``False`` if not. (This validation is applied last in the chain of validations.)
validRequired Boolean indicating whether or not keys that are allowed by the mask, but result in an invalid value are allowed to be entered into the control. Setting this to ``True`` implies that a valid default value is set for the control.
retainFieldValidation ``False`` by default; if True, this allows individual fields to retain their own validation constraints independently of any subsequent changes to the control's overall parameters. (This is a control-level parameter.)
validator Validators are not normally needed for masked controls, because of the nature of the validation and control of input. However, you can supply one to provide data transfer routines for the controls.
raiseOnInvalidPaste ``False`` by default; normally a bad paste simply is ignored with a bell; if True, this will cause a ValueError exception to be thrown, with the .value attribute of the exception containing the bad value.
stopFieldChangeIfInvalid ``False`` by default; tries to prevent navigation out of a field if its current value is invalid. Can be used to create a hybrid of validation settings, allowing intermediate invalid values in a field without sacrificing ability to limit values as with validRequired. NOTE: It is possible to end up with an invalid value when using this option if focus is switched to some other control via mousing. To avoid this, consider deriving a class that defines _LostFocus() function that returns the control to a valid value when the focus shifts. (AFAICT, The change in focus is unpreventable.)
======================== ==================================================================
Coloring Behavior
=================
The following parameters have been provided to allow you to change the default
coloring behavior of the control. These can be set at construction, or via
the .SetCtrlParameters() function. Pass a color as string e.g. 'Yellow':
======================== =======================================================================
emptyBackgroundColour Control Background color when identified as empty. Default=White
invalidBackgroundColour Control Background color when identified as Not valid. Default=Yellow
validBackgroundColour Control Background color when identified as Valid. Default=white
======================== =======================================================================
The following parameters control the default foreground color coloring behavior of the
control. Pass a color as string e.g. 'Yellow':
======================== ======================================================================
foregroundColour Control foreground color when value is not negative. Default=Black
signedForegroundColour Control foreground color when value is negative. Default=Red
======================== ======================================================================
Fields
======
Each part of the mask that allows user input is considered a field. The fields
are represented by their own class instances. You can specify field-specific
constraints by constructing or accessing the field instances for the control
and then specifying those constraints via parameters.
fields
This parameter allows you to specify Field instances containing
constraints for the individual fields of a control, eg: local
choice lists, validation rules, functions, regexps, etc.
It can be either an ordered list or a dictionary. If a list,
the fields will be applied as fields 0, 1, 2, etc.
If a dictionary, it should be keyed by field index.
the values should be a instances of maskededit.Field.
Any field not represented by the list or dictionary will be
implicitly created by the control.
Eg::
fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]
Or::
fields = {
1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
3: ( Field(choices=['01', '02', '03'], choiceRequired=True)
}
The following parameters are available for individual fields, with the
same semantics as for the whole control but applied to the field in question:
============== =============================================================================
fillChar if set for a field, it will override the control's fillChar for that field
groupChar if set for a field, it will override the control's default
defaultValue sets field-specific default value; overrides any default from control
compareNoCase overrides control's settings
emptyInvalid determines whether field is required to be filled at all times
validRequired if set, requires field to contain valid value
============== =============================================================================
If any of the above parameters are subsequently specified for the control as a
whole, that new value will be propagated to each field, unless the
retainFieldValidation control-level parameter is set.
============== ==============================
formatcodes Augments control's settings
excludeChars ' ' '
includeChars ' ' '
validRegex ' ' '
validRange ' ' '
choices ' ' '
choiceRequired ' ' '
validFunc ' ' '
============== ==============================
Control Class Functions
=======================
.GetPlainValue(value=None)
Returns the value specified (or the control's text value
not specified) without the formatting text.
In the example above, might return phone no='3522640075',
whereas control.GetValue() would return '(352) 264-0075'
.ClearValue()
Returns the control's value to its default, and places the
cursor at the beginning of the control.
.SetValue()
Does "smart replacement" of passed value into the control, as does
the .Paste() method. As with other text entry controls, the
.SetValue() text replacement begins at left-edge of the control,
with missing mask characters inserted as appropriate.
.SetValue will also adjust integer, float or date mask entry values,
adding commas, auto-completing years, etc. as appropriate.
For "right-aligned" numeric controls, it will also now automatically
right-adjust any value whose length is less than the width of the
control before attempting to set the value.
If a value does not follow the format of the control's mask, or will
not fit into the control, a ValueError exception will be raised.
Eg::
mask = '(###) ###-####'
.SetValue('1234567890') => '(123) 456-7890'
.SetValue('(123)4567890') => '(123) 456-7890'
.SetValue('(123)456-7890') => '(123) 456-7890'
.SetValue('123/4567-890') => illegal paste; ValueError
mask = '#{6}.#{2}', formatcodes = '_,-',
.SetValue('111') => ' 111 . '
.SetValue(' %9.2f' % -111.12345 ) => ' -111.12'
.SetValue(' %9.2f' % 1234.00 ) => ' 1,234.00'
.SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError
mask = '#{6}.#{2}', formatcodes = '_,-R' # will right-adjust value for right-aligned control
.SetValue('111') => padded value misalignment ValueError: " 111" will not fit
.SetValue('%.2f' % 111 ) => ' 111.00'
.SetValue('%.2f' % -111.12345 ) => ' -111.12'
.IsValid(value=None)
Returns ``True`` if the value specified (or the value of the control
if not specified) passes validation tests
.IsEmpty(value=None)
Returns ``True`` if the value specified (or the value of the control
if not specified) is equal to an "empty value," ie. all
editable characters == the fillChar for their respective fields.
.IsDefault(value=None)
Returns ``True`` if the value specified (or the value of the control
if not specified) is equal to the initial value of the control.
.Refresh()
Recolors the control as appropriate to its current settings.
.SetCtrlParameters(\*\*kwargs)
This function allows you to set up and/or change the control parameters
after construction; it takes a list of key/value pairs as arguments,
where the keys can be any of the mask-specific parameters in the constructor.
Eg::
ctl = masked.TextCtrl( self, -1 )
ctl.SetCtrlParameters( mask='###-####',
defaultValue='555-1212',
formatcodes='F')
.GetCtrlParameter(parametername)
This function allows you to retrieve the current value of a parameter
from the control.
*Note:* Each of the control parameters can also be set using its
own Set and Get function. These functions follow a regular form:
All of the parameter names start with lower case; for their
corresponding Set/Get function, the parameter name is capitalized.
Eg::
ctl.SetMask('###-####')
ctl.SetDefaultValue('555-1212')
ctl.GetChoiceRequired()
ctl.GetFormatcodes()
*Note:* After any change in parameters, the choices for the
control are reevaluated to ensure that they are still legal. If you
have large choice lists, it is therefore more efficient to set parameters
before setting the choices available.
.SetFieldParameters(field_index, \*\*kwargs)
This function allows you to specify change individual field
parameters after construction. (Indices are 0-based.)
.GetFieldParameter(field_index, parametername)
Allows the retrieval of field parameters after construction
The control detects certain common constructions. In order to use the signed feature
(negative numbers and coloring), the mask has to be all numbers with optionally one
decimal point. Without a decimal (e.g. '######', the control will treat it as an integer
value. With a decimal (e.g. '###.##'), the control will act as a floating point control
(i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the
integer control truncates the value. However, for a true numeric control,
masked.NumCtrl provides all this, and true numeric input/output support as well.
Check your controls by calling each control's .IsValid() function and the
.IsEmpty() function to determine which controls have been a) filled in and
b) filled in properly.
Regular expression validations can be used flexibly and creatively.
Take a look at the demo; the zip-code validation succeeds as long as the
first five numerals are entered. the last four are optional, but if
any are entered, there must be 4 to be valid.
masked.Ctrl Configuration
=========================
masked.Ctrl works by looking for a special *controlType*
parameter in the variable arguments of the control, to determine
what kind of instance to return.
controlType can be one of::
controlTypes.TEXT
controlTypes.COMBO
controlTypes.IPADDR
controlTypes.TIME
controlTypes.NUMBER
These constants are also available individually, ie, you can
use either of the following::
from wx.lib.masked import MaskedCtrl, controlTypes
from wx.lib.masked import MaskedCtrl, COMBO, TEXT, NUMBER, IPADDR
If not specified as a keyword argument, the default controlType is
controlTypes.TEXT.
|class_summary| Classes Summary
===============================
================================================================================ ================================================================================
:ref:`~wx.lib.masked.maskededit.Field` This class manages the individual fields in a masked edit control.
:ref:`~wx.lib.masked.maskededit.MaskedEditAccessorsMixin` To avoid a ton of boiler-plate, and to automate the getter/setter generation
:ref:`~wx.lib.masked.maskededit.MaskedEditMixin` This class allows us to abstract the masked edit functionality that could
================================================================================ ================================================================================
|
.. toctree::
:maxdepth: 1
:hidden:
wx.lib.masked.maskededit.Field
wx.lib.masked.maskededit.MaskedEditAccessorsMixin
wx.lib.masked.maskededit.MaskedEditMixin
|