Search code examples
python-2.7wxpython

How to have different colored texts in a wx.StaticText() in wxPython


Level: Beginner

I am developing a GUI with wxPython on Windows 7 OS. I have a question regarding the wx.StaticText() I would like to have two different colors for a text in a wx.StaticText() field. How can I achieve that?

For eg: As shown in the image below I need two different parts of a text to have two different colors. enter image description here

I tried to separate the text into two parts and then applied different colors to them but for some reason the first text fields doesn't appears only second one appears in the GUI. I even tried to use pos=() in wx.StaticText() and other options but nothing worked. In my code I am creating panels in a loop and then inside the loop I am creating wx.StaticText() fields and adding them to a panel. When the loop completes these panels are ultimately added to a BoxSizer.

The code snippet is given below (Please be advised that I have edited the code below from my actual code. My main idea is to know if my approach will solve this problem or not? My code is working fine for one wx.StaticText field, which prints the values in the panels in a same color.):

k = 0
sizer = wx.BoxSizer(wx.VERTICAL)
for i in locations: #locations is defined in other part of the code
    lPanels = 'lPanel'+str(k)
    lPanels = wx.Panel(panel2, size=(screenWidth,50))
    #panel2 and screenWidth are defined in other part of code.
    label0 = str(k+1)+ '. '
    label1 = locations[k]
    text0 = wx.StaticText(lPanels, -1, label0)
    text0.SetForegroundColour('#ffffff')
    text1 = wx.StaticText(lPanels, -1, label1)
    text1.SetForegroundColour('#000001')
    sizer.Add(lPanels, 0, wx.ALL, 5)
    k += 1
panel2.SetSizer(sizer)

Is there a better way to approach this problem? Can some one provide a small example? Thank you. PS: There is a similar kind of an old question here. But it is not answered yet.


Solution

  • I believe your "text1" overlap "text0", that is why "the first text fields doesn't appears only second one appears in the GUI" as you said

    Please try this:

        text0 = wx.StaticText(lPanels, -1, label0, pos=(0,0))
        text0.SetForegroundColour('BLACK')
        text1 = wx.StaticText(lPanels, -1, label1, pos=(50,0))
        text1.SetForegroundColour('BLUE')
    

    EDIT:

    Please check the value of "screenWidth", make sure its width is big enough to contain all the string.

    enter image description here