Tkinter Entry Widget - error if record is not int

I was wondering how I can show an error if the record is not an integer. I was able to make my code accept only a certain range of integers, but I have no way to display an error if the letters are specified instead. I was wondering if anyone could 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 
+4
source share
4 answers

Use str.isdigit() to check if 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 the code will look 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" 
+5
source

You can catch an exception if 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 
+3
source

Well ... you can always format your lines, for example:

 msg = "Error. Invalid value %d. Value must be between 0-255" % c 
0
source
 num = 123 if isinstance(num, int): True 
0
source

Source: https://habr.com/ru/post/1445466/


All Articles