Tkinter Entry Widget - 如果Entry不是int,则出错

时间:2012-11-12 09:17:40

标签: python tkinter

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

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 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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

答案 2 :(得分:0)

嗯......您可以随时格式化字符串,例如:

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

答案 3 :(得分:0)

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