pythonのtkinterでメモ帳作り_改行したとき行頭にインテンドや箇条書きがあれば改行後も引き継ぐ
習慣化2_13日目
どこかで記事をまとめたいが、少しずつ進めたことをメモしていく。
ここで記載している内容を一部改修した記事↓
作成した関数
def check_enter(self): # 改行したとき、もとの行のテキストを取得する # cursor_now = TextArea.index('insert -1lines') # ic| cursor_now: '1.0' pre_row_text = TextArea.get('insert -1lines', 'insert -1lines lineend') # re.matchで行頭の半角全角スペースタブやアスタリスクを取得 gyoto = re.match(r'([ \t]*)([\*\+\-])|([ \t]+)', pre_row_text) # ic| gyoto: <re.Match object; span=(0, 2), match='\t*'> # 取得した行頭がNoneじゃなかったら、その取得内容を改行後の先頭に挿入する if gyoto is not None: TextArea.insert('insert', gyoto.group()+" ") # メイン内での処理 if __name__ == '__main__': (snip) root.bind("<KeyPress-Return>", check_enter)
改行するたびにチェックが入るからか、さすがに少しメモ帳が重くなったかも?
参考にしたページ
テキストエリアの情報を取得する
Textウィジェットでできることが、めちゃくちゃ分かりやすく整理されている
# 改行したとき、もとの行のテキストを取得する # cursor_now = TextArea.index('insert -1lines') # ic| cursor_now: '1.0' pre_row_text = TextArea.get('insert -1lines', 'insert -1lines lineend')
正規表現で行頭の文字列を取得する
re.matchについて
https://note.nkmk.me/python-re-match-search-findall-etc//note.nkmk.me
# 複数文字で区切ったりするため、正規表現を使用する import re (snip) # re.matchで行頭の半角全角スペースタブやアスタリスクを取得 gyoto = re.match(r'([ \t]*)([\*\+\-])|([ \t]+)', pre_row_text) # ic| gyoto: <re.Match object; span=(0, 2), match='\t*'> # 取得した行頭がNoneじゃなかったら、その取得内容を改行後の先頭に挿入する if gyoto is not None: TextArea.insert('insert', gyoto.group()+" ")
いつもありがとうございます!