Search code examples
pythonmethodsdigitswxtextctrl

wxTextCtrl code to detect numbers only in Python


I have constructed a wxTextCtrl and want to return true if ONLY digits are entered by the user.

Here is my Python code:

@staticmethod    
def isAllDigits(s):

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

And my code that calls 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)

For some reason my isAllDigits method is not detecting only digits. For example, If I were to enter "3k5" into the textCtrl, my program returns that "3k5" is all digits and is valid, which is incorrect.

What is wrong with my isAllDigits method?


Solution

  • You can do this way

    @staticmethod    
    def isAllDigits(s):
        s=s.split('.')
        if len(s)>2:
           return false
    
        return all( s.isdigit() for char in s)
    

    or in your method Remove else .. break part