'How to validate a entry in tkinter using python for inputs like 5.0e-7

I want to know how the inputs to an entry widget in tkinter is validated so as to accommodate only digits, '-' symbols and letter 'e'. This widget is going to accept like 5.0e-7.Thanks In advance.



Solution 1:[1]

Two approaches come to mind:

Regex

Check if the user's input matches the pattern of [digits].[digits]e-[digits] with regex:

import re

user_input = '5.0e-7'

if re.match(r'\d+.\d+e-\d+', user_input):
    print('valid')
else:
    print('not valid')

Float

It looks like your widget is expecting exponential-format numbers, in which case python can convert them to a float without the need for regex. This would permit both negative (e.g. 5.0e-7) and positive (e.g. 5.0e7), which may or may not be what you're after:

user_input = '5.0e-7'

try:
    float(user_input)
    print('valid')
except:
    print('not valid')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PangolinPaws