1

这是我到目前为止所拥有的

vdcm = (self.register(self.checkForInt), '%S')
roundsNumTB = Entry(self, validate = 'key', validatecommand = vdcm)

然后 checkForInt() 函数定义为

def checkForInt(self, S):
        return (S.isDigit())

输入框是一个偶数,并且只有一个数字;不是字符。如果输入了一个字符,它就会被拒绝。这只会工作一次。如果输入了字符,则不拒绝作为输入的下一个键击。

如果有人能告诉我如何让它永久检查以确保字符串是一个数字,并且是一个偶数,那将不胜感激。

如果有任何帮助,这是我收到的错误消息

Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "[py directory]", line 101, in checkForInt
    return (S.isDigit())
AttributeError: 'str' object has no attribute 'isDigit'
4

1 回答 1

3

我认为函数调用 isisdigit()和 not isDigit(),注意大小写差异。如果你想测试输入是一个整数,甚至是你必须首先使用int()和测试转换字符串:

def checkForEvenInt(self, S):
    if S.isdigit():
        if int(S) % 2 is 0:
            return True
    return False

请记住,Python 非常区分大小写,包括函数。例如,这是一个 iPython 会话:

In [1]: def my_func(): return True

In [2]: my_func()
Out[2]: True

In [3]: my_Func()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-25-ac6a0a3aba88> in <module>()
----> 1 my_Func()

NameError: name 'my_Func' is not defined
于 2013-11-12T23:06:57.373 回答