Is it possible to limit TextCtrl to accept numbers only in wxPython?

Jeroen Dirks picture Jeroen Dirks · Sep 2, 2009 · Viewed 11.3k times · Source

I want to have a text control that only accepts numbers. (Just integer values like 45 or 366)

What is the best way to do this?

Answer

Jay P. picture Jay P. · Oct 19, 2009

I had to do something similar, checking for alphanumeric codes. The tip on EVT_CHAR was the right thing:

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        self.entry = wx.TextCtrl(self, -1)
        self.entry.Bind(wx.EVT_CHAR, self.handle_keypress)

    def handle_keypress(self, event):
        keycode = event.GetKeyCode()
        if keycode < 255:
            # valid ASCII
            if chr(keycode).isalnum():
                # Valid alphanumeric character
                event.Skip()