user1730056
user1730056

Reputation: 623

Tkinter Entry Widget - Error if Entry is not an int

I was wondering how I can display an error if the entry is not an integer. I was able to make it so my code will only accept a certain range of integers, but I don't have a way to display an error if letters are given instead. I was wondering if someone can shed some knowledge.. Thanks!

def get(self):
    c = int(self.a.get())
    d = int(self.b.get())
    if c>255 or c<0 or d>255 or d<0 :
        print c
        tkMessageBox.showerror("Error2", "Please enter a value between 0-255")
        self.clicked_wbbalance()
    if c<255 and c>0 and d<255 and d>0:
        print "it worked"
        pass

Upvotes: 4

Views: 4024

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Use str.isdigit() to check whether the input is integer or not:

In [5]: "123".isdigit()
Out[5]: True

In [7]: "123.3".isdigit()
Out[7]: False

In [8]: "foo".isdigit()
Out[8]: False

so you code becomes something like this:

def get(self):
    c = self.a.get()
    d = self.b.get()
    if c.isdigit() and d.isdigit():
        c,d=int(c),int(d)
        if c>255 or c<0 or d>255 or d<0 :
            print c
            tkMessageBox.showerror("Error2", "Please enter a value between 0-255")
            self.clicked_wbbalance()
        elif c<255 and c>0 and d<255 and d>0:
            print "it worked"
            pass
    else:
         print "input is not an integer"

Upvotes: 5

fatpudding
fatpudding

Reputation: 1

num = 123
if isinstance(num, int):
True

Upvotes: 0

Tim
Tim

Reputation: 12174

You can catch the exception when there is invalid input.

try:
    c = int(self.a.get())
    d = int(self.b.get())
except ValueError:
    # Show some sort of error message, input wasn't integers
else:
    # Input was integers, continue as normal

Upvotes: 3

Chris
Chris

Reputation: 1643

Well...you can always format your strings, like this for example:

msg = "Error. Invalid value %d. Value must be between 0-255" % c

Upvotes: 0

Related Questions