Click here to Skip to main content
15,030,781 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.I build an app(with tkinter) and I want to check if entry is number.
I use isinstance() ,but when I type 2 ,I receive False.Also, I don't want to use isdigit(),because I want to give negative and positive numbers as input and negative numbers with isdigit is a wrong choice.
How can i fix my problem?
Thanks.

Here I have test:

What I have tried:

Python
from tkinter import *
root = Tk()
root.geometry("1800x1100")

latitude_entry = Entry(root , width = 12)
latitude_entry.place(x = 26 , y = 55 , height = 30)

def check(latitude_entry):
    print(isinstance(latitude_entry.get() , (int)))

bu = Button(root , width = 20,text="press",command=lambda:check(latitude_entry))
bu.place(x = 500 , y = 500)

root.mainloop()
Posted
Updated 17-Mar-21 23:11pm

1 solution

The latitude_entry control is a text box, so when you call isinstance on the content, it returns false because the text "2" is not an integer, it is a string of characters.
You need to try to convert it to an integer, and handle the exception raised when it is not a valid number; something like:
Python
lat = latitude_entry.get()
try:
    x = int(lat)
except ValueError:
    print(lat, "is not a number") // take other action here

You need to add some messaging code inside the except block.
   
Comments
Nick_is_asking 18-Mar-21 6:03am
   
Thank you!!!
Richard MacCutchan 18-Mar-21 6:50am
   
You're welcome. Take a look at Built-in Functions — Python 3.9.2 documentation[^] to see all the others.

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