Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to achieve below situation, below code is part of a TKinter GUI program

Allow empty string
Allow integer
Allow float
Allow period '.' only after atleast a digit
allow entry of only one period '.'
in my below code I am able to achieve

Allow empty string
Allow integer
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.


What I have tried:

First try
Python
<pre>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)




SECOND TRY
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






Python
<pre>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
Posted
Updated 14-Mar-23 19:58pm

1 solution

Use a regex:
RegEx
^(|(\d*(\.\d*)?))$
Shoudl do it.
 
Share this answer
 
Comments
Priyanshu Chandel 15-Mar-23 2:04am    
I tried this, it will have same behavior it wont allow deletion of period '.', however i fixed it by adding extra condition to verify if pressed key is backspace
from keyboard import read_event
elif read_event().name == 'backspace':

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900