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

use*_*056 4 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
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 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
Run Code Online (Sandbox Code Playgroud)

所以你的代码就像这样:

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"
Run Code Online (Sandbox Code Playgroud)