Search code examples
pythonwxpythonfocus

wxPython TextCtrl Not Focusing After using Remove() or Clear()


So I am making my Major Project for my HSC which consists of three banking calculators.

I gather the data from various TextCtrls before doing the calculations. For my Savings Calculator, I have two TextCtrls, one for years and one for months. To make the program more intuitive, I want the respective TextCtrl's value to say 'Years' or 'Months' rather than my StaticText saying 'Savings Term (Years - Months).

However, upon clicking the TextCtrl, it clears the contents of the box, but I cannot focus on the box again after the first click. The clear function still continues to run even though the value is blank and the only way to refocus is via tabbing to the field. Snippets of code are below:

self.SavingLabel4 = wx.StaticText(self.Savings_Pane, -1, "          Savings Term (Years - Months)")
self.Savings_TermYears = wx.TextCtrl(self.Savings_Pane, -1, "Years")
self.Savings_TermYears.Bind(wx.EVT_LEFT_DOWN, self.ClearText123)

def ClearText123(self, event):
    print self.Savings_TermYears.GetValue()     # print the value of the text control
    if self.Savings_TermYears.GetValue != '':    # if the control isn't blank, clear it
        self.Savings_TermYears.Clear()
        print 'Cleared'                        # outputs that the clear function was used (just for testing)

Solution

  • This is a relatively hacky solution, but it works on this case. What happens is, once you click, if the text is "Years", then it clears the whole TextCtrl, then regains focus and finally unbinds that click event from the TextCtrl (since no longer needed):

    def ClearText123(self, event):
        if self.Savings_TermYears.GetValue() == 'Years': # if the control isn't blank, clear it
            self.Savings_TermYears.Clear()
            self.Savings_TermYears.Unbind(wx.EVT_LEFT_DOWN)
        self.Savings_TermYears.SetFocus()