Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Entry Widget - Error if Entry is not an int

Tags:

python

tkinter

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
like image 556
user1730056 Avatar asked Feb 19 '23 12:02

user1730056


1 Answers

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"
like image 118
Ashwini Chaudhary Avatar answered May 19 '23 18:05

Ashwini Chaudhary