I want the user to be able to type only a float (that is, numbers from 0 to 9 and the decimal point shoul开发者_Python百科d show, other characters should not). How can I do that ?
edit I need to get values like "4" or "3.5" or ".9", nothing like "10e23"
Inconsistent values should also be rejected, such as "10.12.45" ...
I've finally an acceptable answer thanks to SO question "How to extract a floating number from a string in Python"
numeric_const_pattern = r"""
[-+]? # optional sign
(?:
(?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
|
(?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
)
# followed by optional exponent part if desired
(?: [Ee] [+-]? \d+ ) ?
"""
self.rx = re.compile(numeric_const_pattern, re.VERBOSE)
in the init part,
and :
def validate_float(self, widget, entry):
entry_text = entry.get_text()
newtext = self.rx.findall(entry_text)
if len(newtext) :
entry.set_text(newtext[0])
else:
entry.set_text("")
connected to the "changed" event of the entry. Many thanks to all those who helped.
I'm not sure if you will get the buffer from the "changed" event.
However, it might be a good idea to have a look at connecting to the signal "preedit-changed" in the entry itself:
The "preedit-changed" signal is emitted when an input method is used, the typed text will not immediately be committed to the buffer. So if you are interested in the text, connect to this signal.
And then when you get the input you can check so that it is valid, and then manipulate the fields value accordingly.
Catch the event fired when the user modifies the value in the entry, and manually validate it's a float. This can be as easy as using a try
around float()
:
>>> float("1.4")
1.4
>>> float("1.4a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 1.4a
>>>
If an exception occurs, reject the value.
Edit: you can filter the characters as they are entered, too.
if newCharacter in "0123456789.":
# valid
else
# invalid
精彩评论