4

我想知道如果条目不是整数,如何显示错误。我能够做到,所以我的代码将只接受一定范围的整数,但如果给出字母,我没有办法显示错误。我想知道是否有人可以提供一些知识.. 谢谢!

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

4 回答 4

5

用于str.isdigit()检查输入是否为整数:

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

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

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

所以你的代码变成了这样:

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"
于 2012-11-12T09:20:52.200 回答
3

当输入无效时,您可以捕获异常。

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
于 2012-11-12T09:21:15.073 回答
0

嗯......你总是可以格式化你的字符串,例如:

msg = "Error. Invalid value %d. Value must be between 0-255" % c
于 2012-11-12T09:20:35.887 回答
0
num = 123
if isinstance(num, int):
True
于 2012-11-12T09:25:21.303 回答