0

我已经构建了一个 wxTextCtrl 并希望在用户仅输入数字时返回 true。

这是我的 Python 代码:

@staticmethod    
def isAllDigits(s):

    for char in list(s):
        if not char.isdigit():
            return False
        else:
            break
    return True 

而我调用 isAllDigits 的代码:

     if self.firstNum.IsEmpty() or not self.isAllDigits(self.firstNum.GetValue()):
        self.dataInputIsValid = False 
        msgStr = "Your first number is invalid, please enter only enter digits and do not leave the field blank."
        wx.MessageBox(msgStr)

    if self.secondNum.IsEmpty() or not self.isAllDigits(self.secondNum.GetValue()):
        self.dataInputIsValid = False 
        msgStr = "Your second number is invalid, please enter only enter digits and do not leave the field blank."
        wx.MessageBox(msgStr)

出于某种原因,我的 isAllDigits 方法不只检测数字。例如,如果我在 textCtrl 中输入“3k5”,我的程序会返回“3k5”是所有数字并且是有效的,这是不正确的。

我的 isAllDigits 方法有什么问题?

4

2 回答 2

1

你可以这样做

@staticmethod    
def isAllDigits(s):
    s=s.split('.')
    if len(s)>2:
       return false

    return all( s.isdigit() for char in s)

或在您的方法中删除else .. break部分

于 2014-09-22T03:32:02.020 回答
0

这次尝试...除了在 pyqt4 Qlineedit 上为我工作

def textBoxNumbersOnly(QlineEdit):
    if QlineEdit.text()!="-" and QlineEdit.text()!="+":
        try:
            float(QlineEdit.text())
        except ValueError:
            QlineEdit.setText(QlineEdit.text()[:-1])
            QlineEdit.setCursorPosition = len(QlineEdit.text())
    pass

如果您以“-”或“+”开头,它不会抛出异常。它允许浮动;不允许出现“3.14.14”之类的错误。它省略了错误的字符并将光标移动到行尾。您可能需要对其进行调整以适用于您的应用程序。

于 2017-03-09T21:29:11.300 回答