Hi I am a beginner on Python and was wondering how you can make a user input a number that contains two decimal places or less
-
Please show us what you tried already. Provide some code in this way the question is invalid for stack overflow. Please read the FAQ. – mybirthname Sep 26 '14 at 22:51
-
This question might be of relevance. http://stackoverflow.com/questions/23307209/checking-if-input-is-a-float-and-has-exactly-2-numbers-after-the-decimal-point – Shaktidhar Dandapani Sep 27 '14 at 13:30
2 Answers
The wx.TextCtrl
constructor takes a validator
argument.
You can use any subclass of wx.Validator
here to implement any validation you want.
Unfortunately, the wxPython docs don't explain how validators work very well, so you have to look at the C++-focused wxValidator
Overview. But wxPython does come with IntValidator
, which makes a nice example.
Note that there are multiple different ways to enforce this.
For example, you could block them from typing any invalid characters. If they try to type .
, it's valid if there isn't already a .
in the string, unless you're more than two digits from the right edge; if they try to type a digit, it's valid unless you're to the right of a .
and there are already two digits there; anything else isn't valid. You'd override OnChar
to provide this kind of enforcement.
Or you could let them type whatever they want, then complain if there are too many digits when they click the OK button. You could truncate their input for them, leave it alone, or wipe it out and make them start all over again. You've override Validate
for that.
Or you could do the complaining when they tab out of the control. Or, instead of complaining, you could just truncate it to two digits and warn them that you'd done so. And so on.

- 354,177
- 51
- 601
- 671
Check out the wxPython demo, I would probably use the wx.lib.masked.numctrl for that.

- 2,086
- 1
- 15
- 14