wxPython: How to change the font color in textctrl with a checkbox?

user1106770 picture user1106770 · Dec 21, 2011 · Viewed 9.3k times · Source

I have some checkboxes like this

self.myCB = wx.CheckBox(panel, id=02, label="someString", pos=(20, 25))

behind every checkbox there's a TextCtrl like this

self.myTC = wx.TextCtrl(panel, value=" 0", id=self.myCB.GetId(), pos=(320, 25), size = wx.Size(80, 20))

when I select the checkbox AND the value of my Textctrl is "0", the font color of my Textctrl should change to red.

I tried it with an if-statement but it doesn't do anything

Answer

robots.jpg picture robots.jpg · Dec 22, 2011

You may have to apply the style wx.TE_RICH to your TextCtrl to change the text color.

Tested:

import wx

class Main(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.text = wx.TextCtrl(self, wx.NewId(), style=wx.TE_RICH)
        self.check = wx.CheckBox(self, wx.NewId(), 'Make text red if 0')
        self.check.Bind(wx.EVT_CHECKBOX, self.onCheck)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.text, 0)
        sizer.Add(self.check, 0)
        self.SetSizerAndFit(sizer)
        self.Show()

    def onCheck(self, evt):
        value = self.text.GetValue()
        if self.check.IsChecked() and value == '0':
            self.text.SetForegroundColour(wx.RED)
        else:
            self.text.SetForegroundColour(wx.BLACK)

app = wx.App(0)
Main(None, -1, 'Checkbox')
app.MainLoop()