How to restrict user to enter only one period '.' that too after a digit

Question:

I am trying to achieve below situation, below code is part of a TKinter GUI program

  1. Allow empty string
  2. Allow integer
  3. Allow float
  4. Allow period ‘.’ only after atleast a digit
  5. allow entry of only one period ‘.’

in my below code I am able to achieve

  1. Allow empty string
  2. Allow integer
  3. Allow float

BACKGROUND – the initial value of this entryBox is fetched from SQlite3 DB which is REAL value either integer or float.
Once the initial value is inserted as 12.36 for example then if I delete all the values and try to type period after a digit or without any digit, it is not possible.
someone can please help to indicate what I am doing wrong.

    def validate_number_decimal_entry(text, current_contents):
    if text.isdigit() or text == '' or (text == '.' and current_contents.count('.') == 1) or (
            text.replace('.', '', 1).isdigit() and
            current_contents.count('.') < 1):
        return True
    else:
        return False

pri_validate_number_entry_cmd = main_GUI.register(validate_number_decimal_entry)

item_pri_ent = Entry(item_list_avail_canv, validate='key',
                     validatecommand=(pri_validate_number_entry_cmd, '%S', '%p'),
                     width=10, font=(None, 12), state=DISABLED)
item_pri_ent.place(x=125, y=35)

UPDATE:

I modified code like below and now it is working as expected to fullfil the requirement mentioned above but it is not allowing to delte period ‘.’ once it is entered by using backspace key from keyboard but if i select entire content of the entry widget using mouse cursor and then press backspace key then can delete because below condition returned True.

(text == ‘.’ and ‘.’ not in current_contents and len(current_contents) >= 1) or text. Replace(‘.’, ”).isdigit()

Can someone help to suggest so I can retain the condition and still can delete period ‘.’ using backspace

def validate_number_decimal_entry(text):
current_contents = item_pri_ent.get()
if text.isdigit() or text == '' or (
        text == '.' and '.' not in current_contents and len(current_contents) >= 1) or text.replace('.', '').isdigit():
    return True
else:
    return False
Asked By: Priyanshu

||

Answers:

I modified the function as below which is working expected. i use keyboard module to detect pressed key is backspace.

from keyboard importread_event()
def validate_number_decimal_entry(text):
    current_contents = item_pri_ent.get()
    if text.isdigit() or text == '' or text.replace('.', '').isdigit():
        return True
    if text == '.':
        if '.' not in current_contents and len(current_contents) >= 1:
            return True
        elif read_event().name == 'backspace':
            return True
        else:
            return False
    else:
        return False
Answered By: Priyanshu