如何设置wxPython中RichTextCtrl的背景颜色

huangapple go评论72阅读模式
英文:

how to set the background color of a RichTextCtrl in wxPython

问题

class ChatDisplayer(RichTextCtrl):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)

    def addMessage(self, message, red, green, blue):
        font = Font(12, DEFAULT, NORMAL, NORMAL, False)
        text_attr = RichTextAttr()
        text_attr.SetTextColour(BLACK)
        text_attr.SetFont(font)
        bg_color = Colour(red=red, green=green, blue=blue)
        text_attr.SetBackgroundColour(bg_color)

        self.BeginStyle(text_attr)
        self.AppendText(message)
        self.EndStyle()

# The main class is complex but looks like this:
class ChatMessageGrid(FlexGridSizer):
    def __init__(self, panel):
        super().__init__(6, 2, 9, 25)
    
        chat_message_apikey_label = StaticText(panel, label="API key")
        chat_message_apikey_input = TextCtrl(panel)

        chat_displayer_label = StaticText(panel, label="Chat", pos=(1, 0))
        chat_displayer_input = ChatDisplayer(panel, ID_ANY, style=TE_MULTILINE|TE_READONLY)

        chat_message_system_label = StaticText(panel, label="System")
        chat_message_system_input = TextCtrl(panel)

        chat_message_label = StaticText(panel, label="your message")
        chat_message_text = TextCtrl(panel, style=TE_MULTILINE)
        chat_message_button = Button(panel, label="send")

        model_choice_label = StaticText(panel, label="model")
        model_choice_box = ComboBox(panel, value="bbb", choices=model_choices)

        self.AddMany(
        [
            chat_message_apikey_label,
            (chat_message_apikey_input, 1, EXPAND),
            chat_message_system_label,
            (chat_message_system_input, 1, EXPAND),
            (chat_displayer_label, 1, EXPAND),
            (chat_displayer_input, 1, EXPAND),
            (chat_message_label, EXPAND),
            (chat_message_text, 1, EXPAND),
            (model_choice_label, EXPAND),
            (model_choice_box, EXPAND),
            (chat_message_button, EXPAND),
            ]
        )

        self.AddGrowableRow(2, 1)
        self.AddGrowableRow(3, 1)
        self.AddGrowableCol(1, 1)

        chat_message_button.Bind(
            EVT_BUTTON,
            lambda event: self.onClick(
            event,
            chat_message_system_input,
            chat_message_apikey_input,
            chat_displayer_input,
            chat_message_text,
            model_choice_box,
            chat_message_button
            ),
        )

    def completeRequest(self, messages, model, apiKey, chat_displayer_input, message, button):
        # call the service
        userMessage = "User:\n"
        aiMessage = "Assistant:\n"

        # update the UI
        CallAfter(chat_displayer_input.addMessage, userMessage, 176, 210, 167)
        #CallAfter(chat_displayer_input.addMessage, aiMessage, 176, 210, 167)

        # re enable the button
        button.Enable()

    def onClick(
        self,
        event,
        chat_message_system_input: TextCtrl,
        chat_message_apikey_input: TextCtrl,
        chat_message_historic_input: ChatDisplayer,
        chat_message_text: TextCtrl,
        model_choice_box: ComboBox,
        button: Button
    ):
        if not len(chat_message_apikey_input.GetValue().strip()):
            MessageBox("API key is empty!", "Error", OK | ICON_ERROR)
        elif not len(chat_message_text.GetValue().strip()):
            MessageBox("type something please!", "Error", OK | ICON_ERROR)
        else:
            apiKey = chat_message_apikey_input.GetValue().strip()
            message = chat_message_text.GetValue().strip()

        button.Disable()

        # create a thread to run the API call
        t = threading.Thread(target=self.completeRequest, args=(messages, 
        model_choice_box.GetValue(), apiKey, chat_message_historic_input, message, 
        button))
        t.start()
英文:

I have a chatbox and I'm trying to colour every message with a different colour

class ChatDisplayer(RichTextCtrl):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
def addMessage(self, message, red, green, blue):
font = Font(12, DEFAULT, NORMAL, NORMAL, False)
text_attr = RichTextAttr()
text_attr.SetTextColour(BLACK)
text_attr.SetFont(font)
bg_color = Colour(red=red, green=green, blue=blue)
text_attr.SetBackgroundColour(bg_color)
self.BeginStyle(text_attr)
self.AppendText(message)
self.EndStyle()

this does append the text but it does not change the colour of the text of the background colour.
I can find the SetBackgroundColor attribute in the source code but not in the doc.

The main class is complex but looks like this:

class ChatMessageGrid(FlexGridSizer):
def __init__(self, panel):
super().__init__(6, 2, 9, 25)
chat_message_apikey_label = StaticText(panel, label="API key")
chat_message_apikey_input = TextCtrl(panel)
chat_displayer_label = StaticText(panel, label="Chat", pos=(1, 0))
chat_displayer_input = ChatDisplayer(panel, ID_ANY, style=TE_MULTILINE|TE_READONLY)
chat_message_system_label = StaticText(panel, label="System")
chat_message_system_input = TextCtrl(panel)
chat_message_label = StaticText(panel, label="your message")
chat_message_text = TextCtrl(panel, style=TE_MULTILINE)
chat_message_button = Button(panel, label="send")
model_choice_label = StaticText(panel, label="model")
model_choice_box = ComboBox(panel, value="bbb", choices=model_choices)
self.AddMany(
[
chat_message_apikey_label,
(chat_message_apikey_input, 1, EXPAND),
chat_message_system_label,
(chat_message_system_input, 1, EXPAND),
(chat_displayer_label, 1, EXPAND),
(chat_displayer_input, 1, EXPAND),
(chat_message_label, EXPAND),
(chat_message_text, 1, EXPAND),
(model_choice_label, EXPAND),
(model_choice_box, EXPAND),
(chat_message_button, EXPAND),
]
)
self.AddGrowableRow(2, 1)
self.AddGrowableRow(3, 1)
self.AddGrowableCol(1, 1)
chat_message_button.Bind(
EVT_BUTTON,
lambda event: self.onClick(
event,
chat_message_system_input,
chat_message_apikey_input,
chat_displayer_input,
chat_message_text,
model_choice_box,
chat_message_button
),
)
def completeRequest(self, messages, model, apiKey, chat_displayer_input, message, 
button):
# call the service
userMessage = "User:\n"
aiMessage = "Assistant:\n"
# update the UI
CallAfter(chat_displayer_input.addMessage, userMessage, 176, 210,167)
#CallAfter(chat_displayer_input.addMessage, aiMessage, 176, 210,167)
# re enable the button
button.Enable()
def onClick(
self,
event,
chat_message_system_input: TextCtrl,
chat_message_apikey_input: TextCtrl,
chat_message_historic_input: ChatDisplayer,
chat_message_text: TextCtrl,
model_choice_box: ComboBox,
button: Button
):
if not len(chat_message_apikey_input.GetValue().strip()):
MessageBox("API key is empty!", "Error", OK | ICON_ERROR)
elif not len(chat_message_text.GetValue().strip()):
MessageBox("type something please!", "Error", OK | ICON_ERROR)
else:
apiKey = chat_message_apikey_input.GetValue().strip()
message = chat_message_text.GetValue().strip()
button.Disable()
# create a thread to run the API call
t = threading.Thread(target=self.completeRequest, args=(messages, 
model_choice_box.GetValue(), apiKey, chat_message_historic_input, message, 
button))
t.start()

答案1

得分: 1

I assume it is because you are appending the text and it is using the attributes that are currently in force at that position.
你假设是因为你正在“添加”文本,并且它使用当前位置上生效的属性。

Your options would be to change the attributes at the current position or insert the text with a write and new attributes.
你的选择是更改当前位置的属性或使用write和新属性插入文本。

e.g.
例如。

import wx
导入 wx
import wx.richtext
导入 wx.richtext

class MainFrame(wx.Frame):
类 MainFrame(wx.Frame):

def __init__(self):
def __init__(self):
wx.Frame.__init__(self, None, title='Test RichTextCtrl')
wx.Frame.__init__(self, None, title='测试 RichTextCtrl')
self.panel = wx.Panel(self)
self.panel = wx.Panel(self)
self.text1 = wx.richtext.RichTextCtrl(self.panel, value="Rolf is not a surfer,\nbut he likes to the beach", pos=(10,10), style =  wx.TE_MULTILINE | wx.VSCROLL, size=(300, 90))
self.text1 = wx.richtext.RichTextCtrl(self.panel, value="Rolf 不是冲浪者,\n但他喜欢去海滩", pos=(10,10), style =  wx.TE_MULTILINE | wx.VSCROLL, size=(300, 90))
self.button = wx.Button(self.panel, -1, "Insert",pos=(10,110))
self.button = wx.Button(self.panel, -1, "插入",pos=(10,110))
self.button.Bind(wx.EVT_BUTTON, self.On_Button)
self.button.Bind(wx.EVT_BUTTON, self.On_Button)
self.text1.Enable(False)
self.text1.Enable(False)
self.Show()
self.Show()
def On_Button(self, event):
def On_Button(self, event):
self.text1.SetInsertionPoint(34)
self.text1.SetInsertionPoint(34)
text_attr = wx.richtext.RichTextAttr()
text_attr = wx.richtext.RichTextAttr()
text_attr.SetTextColour(wx.GREEN)
text_attr.SetTextColour(wx.GREEN)
bg_color = wx.Colour(red=255, green=0, blue=0)
bg_color = wx.Colour(red=255, green=0, blue=0)
text_attr.SetBackgroundColour(bg_color)
text_attr.SetBackgroundColour(bg_color)
self.text1.BeginStyle(text_attr)
self.text1.BeginStyle(text_attr)
self.text1.WriteText(" to go")
self.text1.WriteText(" 去")
self.text1.EndStyle()
self.text1.EndStyle()
self.text1.SetInsertionPoint(-1)
self.text1.SetInsertionPoint(-1)
bg_color = wx.Colour(red=255, green=255, blue=0)
bg_color = wx.Colour(red=255, green=255, blue=0)
text_attr.SetBackgroundColour(bg_color)
text_attr.SetBackgroundColour(bg_color)
text_attr.SetTextColour(wx.RED)
text_attr.SetTextColour(wx.RED)
self.text1.BeginStyle(text_attr)
self.text1.BeginStyle(text_attr)
self.text1.WriteText(" on hot days")
self.text1.WriteText(" 在炎热的天气上")
self.text1.EndStyle()
self.text1.EndStyle()

if name == 'main':
如果 name == 'main':
app = wx.App()
app = wx.App()
frame = MainFrame()
frame = MainFrame()
app.MainLoop()
app.MainLoop()

英文:

I assume it is because you are appending the text and it is using the attributes that are currently in force at that position.
Your options would be to change the attributes at the current position or insert the text with a write and new attributes.
e.g.

import wx
import wx.richtext
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Test RichTextCtrl')
self.panel = wx.Panel(self)
self.text1 = wx.richtext.RichTextCtrl(self.panel, value="Rolf is not a surfer,\nbut he likes to the beach", pos=(10,10), style =  wx.TE_MULTILINE | wx.VSCROLL, size=(300, 90))
self.button = wx.Button(self.panel, -1, "Insert",pos=(10,110))
self.button.Bind(wx.EVT_BUTTON, self.On_Button)
self.text1.Enable(False)
self.Show()
def On_Button(self, event):
self.text1.SetInsertionPoint(34)
text_attr = wx.richtext.RichTextAttr()
text_attr.SetTextColour(wx.GREEN)
bg_color = wx.Colour(red=255, green=0, blue=0)
text_attr.SetBackgroundColour(bg_color)
self.text1.BeginStyle(text_attr)
self.text1.WriteText(" to go")
self.text1.EndStyle()
self.text1.SetInsertionPoint(-1)
bg_color = wx.Colour(red=255, green=255, blue=0)
text_attr.SetBackgroundColour(bg_color)
text_attr.SetTextColour(wx.RED)
self.text1.BeginStyle(text_attr)
self.text1.WriteText(" on hot days")
self.text1.EndStyle()
if __name__ == '__main__':
app = wx.App()
frame = MainFrame()
app.MainLoop()

huangapple
  • 本文由 发表于 2023年4月10日 22:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定