Python/tkinterプログラミング Textオブジェクトへの文字列挿入

Python/tkinterプログラミングでは、Textオブジェクトで複数行文字列を扱います。

今回は、複数行文字列へ別の文字列を挿入するプログラムを書いて、動作を調べたいと思います。

サンプルプログラム

Textオブジェクトの挙動を調べるにあたり、以下のようなプログラムを作成しました。

■text_insert_sample.py

# 複数行に別の文字列を挿入するプログラム
import sys
import tkinter as tk

def main(position):
    def init_text(msg):
        text.insert(tk.END, msg)

    def click_insert(position):
        text.insert(position, '[***]')

    root = tk.Tk()
    root.title('複数行へのテキスト挿入')

    text = tk.Text(width=40, height=5)
    text.pack()

    init_text('''0123456
ABCDEFG
HIJKLMN''')

    btn = tk.Button(text='挿入', command=lambda:click_insert(position))
    btn.pack()

    root.mainloop()

if __name__ == '__main__':
    position = sys.argv[1]
    main(position)

何をしているのかと言いますと、コマンドライン引数でText#insert()メソッドの第一引数、すなわち挿入位置を指定し、どのように表示されるのかを調べるというものです。

Textオブジェクトには予め3行のテキストを表示ししておき、挿入ボタンのクリックによって”[***]”という文字列を挿入位置に表示します。

実験結果

挿入位置をいろいろ変えてプログラムを実行したところ、以下のようになりました。

■1行目の先頭に挿入する

$ python text_insert_sample.py 1.0

■2行目の先頭に挿入する

$ python text_insert_sample.py 2.0

■文字列の最後に挿入する(実際は、文字列の最後尾の次)

$ python text_insert_sample.py 'end'

■文字列の最後の1文字前(実際は最後尾)に挿入する

$ python text_insert_sample.py 'end-1c'


※『end』が最後尾の次の文字を表すため、上の結果と同じになる。

■文字列の最後の2文字前(実際は1文字前)に挿入する

$ python text_isnert_sample.py 'end-2c'

参考文献

Pythonでつくるゲーム開発入門講座 (廣瀬豪)