Last Update: 08.04.2007. By kerim in gui | python
I am not sure if wxPython has a textfield allowing only for numbers (floats or ints).
I found an old mailinglist entry for such a thing and made some changes to the code.
Why would i need that ?
For a small GUI for HDDCleaner for example ?
Anyway here is the code:
import wx
#------------------- stuff to test functionality start ---------
class TestApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, "Numerical Textfield")
frame.Show(True)
self.SetTopWindow(frame)
return True
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition, wx.Size(300, 150))
panel = wx.Panel(self, -1)
self.textfield = NumericTextfield(panel, 10, "", wx.Point(20, 10), wx.Size(100, 20))
self.intButton = wx.Button(panel, -1,label='int',pos=(100,50))
self.floatButton = wx.Button(panel, -1,label='float',pos=(200,50))
self.intButton.Bind(wx.EVT_BUTTON, self.GetInt)
self.floatButton.Bind(wx.EVT_BUTTON, self.GetFloat)
def GetInt(self,event):
print self.textfield.GetIntValue()
def GetFloat(self,event):
print self.textfield.GetFloatValue()
#------------------- stuff to test functionality end ---------
#logic goes here
class NumericTextfield(wx.TextCtrl):
def __init__(self, parent, ID, title,
position, size, allowFloat=True):
wx.TextCtrl.__init__(self, parent, ID, title,
position, size)
wx.EVT_CHAR(self, self.OnChar)
self.allowFloat=allowFloat
def OnChar(self, event):
key = event.GetKeyCode()
#print event.GetKey
if key > 47 and key < 58: #range for numbers
event.Skip()
#we allow only for one decimal point and only if we want a floatfield
elif key == 46 and self.allowFloat==True:
if '.' not in self.GetValue():
if self.GetInsertionPoint() != 0:
event.Skip()
elif key == 8 or key == 127: #backspace and del
event.Skip()
elif key> 314 and key < 318: #cursor left up, right and down
event.Skip()
print key
#retrieve the value as float
def GetFloatValue(self):
return float(self.GetValue())
#retrieve the value as int
def GetIntValue(self):
return int(float(self.GetValue()))
#------------------- stuff to test functionality start ---------
app = TestApp(0)
app.MainLoop()