2noの日記

メモ用

【wxPython】テキストエリアに行数を表示

StyledTextCtrl を使えば簡単に実装出来る。
試しに以前作った 『Markdown をライブプレビュー』に加えてみる。
【wxPython】Markdown をライブプレビュー - 2noの日記

# -*- coding: utf-8 -*-

import wxversion
wxversion.select("3.0")
import wx
import wx.html2
import wx.stc as stc
import markdown

def update(event):
    timer.Start(milliseconds=100, oneShot=True)
    event.Skip()

def update_preview(event):
    browser.SetPage(convert_by_str(text.GetValue()), "")
    event.Skip()

def convert_by_str(str):
    codehilite = "codehilite(force_linenos=True, guess_lang=False, css_class=syntax)"
    html = markdown.markdown(str, ["extra", codehilite])
    return html

if __name__ == "__main__":
    app   = wx.App()
    frame = wx.Frame(None, wx.ID_ANY, "Markdown test")
    sizer = wx.BoxSizer(wx.HORIZONTAL)

    text  = stc.StyledTextCtrl(frame, wx.ID_ANY)
    text.SetMarginType(1, stc.STC_MARGIN_NUMBER)
    text.SetMarginWidth(1, 30)
    text.StyleSetSpec(stc.STC_STYLE_LINENUMBER,  "fore:#999999")
    text.Bind(wx.EVT_CHAR, update)

    browser = wx.html2.WebView.New(frame)
    sizer.Add(text, 1, wx.EXPAND, 10)
    sizer.Add(browser, 1, wx.EXPAND, 10)
    frame.SetSizer(sizer)
    frame.SetSize((640, 480))
    timer = wx.Timer(frame)
    frame.Bind(wx.EVT_TIMER, update_preview, timer)
    frame.Show()
    app.MainLoop()

行数を表示するには、StyledTextCtrl を使い、text.SetMarginType(1, stc.STC_MARGIN_NUMBER) を実行する必要がある。
この情報が少なくて結構探しまわった。
【参考】wx.stc.StyledTextCtrl 增加行号 - Python||C - 博客频道 - CSDN.NET

f:id:wakuworks:20141118121316p:plain