Kaya311
Kaya311

Reputation: 565

wxPython: How to clear default text in TextCtrl with one click

I am making a GUI using wxPython, and I have a text box that requires user input:

self.boxQuantity = wx.TextCtrl(panel, value="Enter quantity", pos=(100, 150), size=(100, 30))
self.Bind(wx.EVT_TEXT, self.getQuantity, self.boxQuantity)

I want the user to be able to click on the text box, and "Enter quantity" to disappear immediately, instead of having to use backspace. Is this possible?

I'm using Windows 10, Python 2.7.9.

Upvotes: 7

Views: 9245

Answers (2)

Legorooj
Legorooj

Reputation: 2757

I know that this question is old, but wxPython now (4.1) has a new SetHint function for a TextCtrl:

text = wx.TextCtrl(self)
text.SetHint('First name')  # This text is grey, and disappears when you type

Upvotes: 11

Joran Beasley
Joran Beasley

Reputation: 113948

I think you want

def toggle1(evt):
    if self.boxQuantity.GetValue() == "Enter quantity":
        self.boxQuantity.SetValue("")
    evt.Skip()
def toggle2(evt):
    if self.boxQuantity.GetValue() == "":
        self.boxQuantity.SetValue("Enter quantity")
    evt.Skip()    

self.boxQuantity.Bind(wx.EVT_FOCUS,toggle1)
self.boxQuantity.Bind(wx.EVT_KILL_FOCUS,toggle2)

its probably better to create a subclass

import wx
class PlaceholderTextCtrl(wx.TextCtrl):
    def __init__(self, *args, **kwargs):
        self.default_text = kwargs.pop("placeholder", "")
        wx.TextCtrl.__init__(self, *args, **kwargs)
        self.OnKillFocus(None)
        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

    def OnFocus(self, evt):
        self.SetForegroundColour(wx.BLACK)
        if self.GetValue() == self.default_text:
            self.SetValue("")
        evt.Skip()

    def OnKillFocus(self, evt):
        if self.GetValue().strip() == "":
            self.SetValue(self.default_text)
            self.SetForegroundColour(wx.LIGHT_GREY)
        if evt:
            evt.Skip()

# then sometime later...

self.text_entry1 = PlaceHolderTextCtrl(self,-1,placeholder="Enter Value")

something like that at least ...

Upvotes: 6

Related Questions