[파이썬] wxPython `wx.RichTextCtrl`: 포맷된 텍스트

Formatting text can greatly enhance the visual presentation and readability of your Python applications. In wxPython, the wx.RichTextCtrl class provides a powerful and flexible way to incorporate formatted text into your GUI.

Creating a RichTextCtrl

To get started, let’s create a basic wx.RichTextCtrl widget:

import wx

app = wx.App()
frame = wx.Frame(None, title="RichTextCtrl Example")
text_ctrl = wx.richtext.RichTextCtrl(frame, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER)

frame.Show()
app.MainLoop()

In this example, we create an instance of wx.RichTextCtrl and add it to a frame. We also specify some styles to enable vertical and horizontal scrollbars.

Formatting Text

Now that we have a RichTextCtrl widget, we can apply different formatting options to the text. Let’s see some common formatting techniques:

Changing Text Color

To change the color of a specific piece of text, you can use the wx.TextAttr class. Here’s how you can change the color of a word:

text_ctrl.BeginTextColour(wx.Colour(255, 0, 0))  # red color
text_ctrl.WriteText("Hello")
text_ctrl.EndTextColour()

In this example, we set the text color to red before writing the word “Hello” to the control. Afterwards, we reset the text color back to its default value using EndTextColour().

Applying Bold and Italic Styles

To apply bold and italic styles to text, you can use the wx.TextAttr class as well. Here’s how you can make a word bold and italic:

text_ctrl.BeginFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_BOLD))
text_ctrl.WriteText("Hello World")
text_ctrl.EndFont()

In this example, we set the font to bold and italic before writing the phrase “Hello World” to the control. Afterwards, we reset the font back to its default value using EndFont().

Adding Bulleted Lists

To create bulleted lists in wx.RichTextCtrl, you can use the wx.richtext.RichTextListStyle class. Here’s how you can create a simple bulleted list:

list_style = wx.richtext.RichTextListStyle()
list_style.SetBulletName("wxRICHTEXT_BULLET_DOT")
text_ctrl.SetBasicStyle(list_style)
text_ctrl.WriteText("Item 1\n")
text_ctrl.WriteText("Item 2\n")
text_ctrl.WriteText("Item 3\n")

In this example, we create a RichTextListStyle object and set its bullet name to “wxRICHTEXT_BULLET_DOT”, which represents a simple dot bullet. We then set this style as the basic paragraph style for the RichTextCtrl and add three items to the list.

Conclusion

The wx.RichTextCtrl widget in wxPython provides a powerful tool for working with formatted text in Python applications. With its wide range of formatting options, you can easily enhance the presentation of your text and create professional-looking documents. Experiment with different formatting styles and unleash the full potential of wx.RichTextCtrl in your projects.