简体   繁体   English

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

[英]Tkinter Entry Widget - Error if Entry is not an int

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

Use str.isdigit() to check whether the input is integer or not: 使用str.isdigit()检查输入是否为整数:

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"

You can catch the exception when 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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM