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?
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?
IntCtrl
, Masked Edit Control
, and NumCtrl
are all designed to do just this, with different levels of control. Checkout the wx demo under "More Windows/Controls" to see how they work.
(Or, if you're instead really looking forward to doing this directly with a raw TextCtrl, I think you'd want to catch EVT_CHAR events, test the characters, and call evt.Skip() if it was an allowed character.)
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()