import wx
class DefaultTextCtrl(wx.TextCtrl):
def __init__(self, defaultText, *args, **kwargs):
self.defaultText = defaultText
wx.TextCtrl.__init__(self, *args, **kwargs)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)
self.SetFocus()
@property
def defaultText(self):
return self.__defaultText
@defaultText.setter
def defaultText(self, defaultText):
self.__defaultText = defaultText
def OnSetFocus(self, evt):
if self.defaultText in (None, ''):
evt.Skip()
return
currText = self.GetValue()
self.SetForegroundColour(wx.Colour(0, 0, 0))
if currText == self.defaultText:
self.SetValue('')
evt.Skip()
def OnKillFocus(self, evt):
if self.defaultText in (None, ''):
evt.Skip()
return
currText = self.GetValue()
if currText == '':
self.SetValue(self.defaultText)
self.SetForegroundColour(wx.Colour(119, 119, 119))
evt.Skip()
def OnTextEnter(self, evt):
evt.EventObject.Navigate()
evt.Skip()
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
bSizer1 = wx.BoxSizer(wx.VERTICAL)
self.panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
sizer = wx.BoxSizer(wx.VERTICAL)
ctrl = wx.SearchCtrl(self.panel)
ctrl.SetDescriptiveText('Name')
ctrl.ShowSearchButton(False)
sizer.Add(ctrl, 0, wx.ALL, 5)
defaultTextCtrl = DefaultTextCtrl("First Name", self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
sizer.Add(defaultTextCtrl, 0, wx.ALL, 5)
defaultTextCtrl1 = DefaultTextCtrl("Last Name", self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize, 0)
sizer.Add(defaultTextCtrl1, 0, wx.ALL, 5)
self.panel.SetSizer(sizer)
self.panel.Layout()
sizer.Fit(self.panel)
bSizer1.Add(self.panel, 1, wx.EXPAND | wx.ALL, 5)
self.SetSizer(bSizer1)
self.Layout()
self.Centre(wx.BOTH)
if __name__ == '__main__':
# creating an app
app = wx.App()
frame = MyFrame(None, title='TextCtrl Default Text Example', )
frame.Show()
app.MainLoop()