I'm having a strange behaviour with wx.richtext.RichTextCtrl. I have a panel containing a read only RichTextCtrl containing some text info about an object and a button updating the content on click. Depending of where the user put the cursor on the RichTextCtrl every bit of text not formatted with BeginTextColour/EndTextColour (or BeginBold/EndBold) will change font style and colour.
I have made a small example displaying the same behaviour:
import wx
import wx.richtext
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='RichTextCtrl')
panel = wx.Panel(self)
self.richTextCtrl = wx.richtext.RichTextCtrl(panel, pos=(5, 5), size=wx.Size(150, 100))
self.button = wx.Button(panel, label='Update', pos=(5, 110))
self.button.Bind(wx.EVT_BUTTON, self.buttonPressed)
self.Show()
def buttonPressed(self, event):
self.richTextCtrl.Clear()
self.richTextCtrl.BeginBold()
self.richTextCtrl.WriteText("abcd")
self.richTextCtrl.EndBold()
self.richTextCtrl.Newline()
self.richTextCtrl.WriteText("abcd")
self.richTextCtrl.Newline()
self.richTextCtrl.BeginTextColour((255, 0, 0))
self.richTextCtrl.WriteText("abcd")
self.richTextCtrl.EndTextColour()
self.richTextCtrl.Newline()
self.richTextCtrl.BeginTextColour((0, 0, 0))
self.richTextCtrl.WriteText("abcd")
self.richTextCtrl.EndTextColour()
if __name__ == '__main__':
app = wx.App()
frame = MyFrame()
app.MainLoop()
This will display a window with a richtextctrl and a button. The click on the button will clear the richtextctrl and add a few lines of text with various styling options. Clicking on a red line of text and then clicking on the update button will write everything in the control not between Begin/EndTextColour in red. Same thing with the the line with bold text, selecting it then clicking the button will put all the text in bold.
I'm not sure if I'm not using richtextctrl the proper way or if I found a bug.
I tried with wxPython 4.0.4 + Python 3.7.5 and wxPython 4.1.0 + Python 3.8.5 on Windows 10 64 bits.
You are inheriting the wx.TextAttr
from the position that you are clicking on.
The style remains in force unless changed.
To fix your issue, reset the style after clearing the text i.e.
def buttonPressed(self, event):
self.richTextCtrl.Clear()
self.richTextCtrl.SetDefaultStyle(wx.TextAttr()) # add this line