Search code examples
pythonpython-2.7wxpython

Check for BS (backspace) in User Input


The following is a routine I use to validate user's inputs into various textCtrl fields:

def OnChar(self, evt):
    key = chr(evt.GetKeyCode())
    if self.flag  == LETTERS and key not in string.letters:
        return
    if self.flag  == DECIMAL_DIGITS and key not in string.digits:
        return
    if self.flag  == HEX_DIGITS and key not in string.hexdigits:
        return
    if self.flag  == NUMERIC and key not in '0123456789.':
        return
    if self.flag  == DATE_TIME and key not in '0123456789/: ':
        return
    evt.Skip()

The problem I have hit is that once you start keying in the data it does not allow you to enter BS. Is there a relatively easy way of allowing this?

Thank you...


Solution

  • You can just filter for those keys and skip the event to ensure that the backspace (or other function keys) are evaluated:

    def OnChar(self, evt):
    
        key = chr(evt.GetKeyCode())
        if ord(key) in [wx.WXK_BACK, wx.WXK_DELETE]:
            evt.Skip()
        if self.flag  == LETTERS and key not in string.ascii_letters:
            return
        if self.flag  == DECIMAL_DIGITS and key not in string.digits:
            return
        if self.flag  == HEX_DIGITS and key not in string.hexdigits:
            return
        if self.flag  == NUMERIC and key not in '0123456789.':
            return
        if self.flag  == DATE_TIME and key not in '0123456789/: ':
            return
        evt.Skip()
    

    You can check the names of those keycodes in the wx Python KeyEvent Documentation.

    Lokla