简体   繁体   中英

Validating user input using tkinter entry python 3

I have a text box and a label on a form. I need to get the data from the entry box and check to make sure its a float.

    nameOfText = (textboxName.get())
    ra = float(textboxra.get())

    if type(ra) == float:
        print("Its a number")
    else:
        print("Not number")

The form works well and when the program runs it will work. If I enter 7 into the textbox it will print (7.0) which is great. If i enter another number and press the 'Go' button it will say 'ValueError: could not convert string to float: 'd''

Ideally, I would like it to clear the text box. I can get a messagebox to appear but cannot get it to clear the textbox again.

Help please.

For clearing the text field you can use delete() . For deleting content from start to finish in an Entry widget you need to define the index at "0" through "end". For the Text widget you need to define row and character index. delete() uses a string to indicate the row and columns. So "1.12" would be the first row and 12th character. As pointed out by @BryanOakley delete() will take the number value of 1.0 but you should use a string to prevent the value/index being read incorrectly for other numbers.

# for Entry widget clear.
textboxName.delete("0", "end")
# for Text widget clear.
textboxName.delete("1.0", "end")

For checking if the variable type is a float:

You can use isinstance() to check if the variable is a float or not.

x = 5
y = 5.0

if isinstance(x, float) == True:
    print(x,"Is float")
else:
    print(x,"Is not a float")

if isinstance(y, float) == True:
    print(y,"Is float")
else:
    print(y,"Is not a float")

Results:

5 Is not a float

5.0 Is float

On the other hand you could use try/except . People will say to use duck typing (asking for forgiveness vs permission). If you are expecting to always see a float then just try it. If you happen to not get a float where it was expected then throw exception.

x = 5
y = "String of text"

try:
    print(float(x))
except:
    print(x,"Cannot be a float")

try:
    print(float(z))
except:
    print(y,"Cannot be a float")

Results:

5.0

String of text Cannot be a float

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM