Python.use(better,Tkinter)《60》事例:クイックリファレンスツール(3)

記事一覧《こちらに移動中です》2007年4月27日 (金)

Python.use(better, Tkinter)
事例:クイックリファレンスツール(3)《Python3.1》

《著》森こねこ・小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第1版♪2006/10/28

■ 概要

Text 部品の機能を紹介するとともに、このアプリケーションのために作成したコードの断片を示します。

この連載では、Tkinter によるオブジェクト指向プログラミングへの扉を開きます。

■ 関連記事

前の記事次の記事

《60》事例:クイックリファレンスツール(3)

    ...
    def dir_text(self, text, subject):
        def tagNames(index, bg, sq):
            index1 = index2 = index
            s = []
            for e in dirs:
                index1 = text.search(pattern=e, index=index2)
                index2 = "%s +%i chars"%(index1, len(e))
                s.append((index1, e))
                text.tag_config(tagName=e, background=bg)
                text.tag_bind(tagName=e, sequence=sq, func=func)
                text.tag_add(e, index1, index2)
            return s

ここでは「《55》テキスト属性(2)」で紹介したのと同様に、各項目を検索 search するとともに、個別のタグ情報を設定 tag_bind します。このとき、パターンを検索 search するたびに、その位置 index を更新します。

        ...
        def func(e):
            index1 = e.widget.index(index=CURRENT)
            for index2, tag in indexTag:
                if text. compare(index1, "<=", index2): break
                pattern = tag
            match = self.helpText.search(pattern="|  %s"%pattern, 
                index="1.0", stopindex=END)
            if match: self.helpText.see(index=match)
        dirs = dir(subject)
        text.insert(END, "%s\n"%dirs)
        indexTag = tagNames(
            index="2.0", bg="yellow", sq="")

index(self,index) は、位置 index= を書式文字列 'line.char' として獲得します。ここで CURRENT を指定すると、選択している位置を指します。

compare(self,index1,op,index2) は、演算子 op を使って、位置 index1= と index2= とを大小比較します。ここでは、条件式 index1<=index2 を満たすときに、ひとつ手前のタグ項目 pattern=tag を、次の検索対象にします。

    ...
    def footer_text(self, text):
        self.image = PhotoImage(file="image/select_prev.gif")
        self.button = Button(text, image=self.image, 
            command=lambda: text.see(index="1.0"))
        text.window_create(index=END, window=self.button)

footer_text は、末尾行に矢印ボタンを設定します。ボタンを選択すると、先頭行までスクロールして、頭文字の一覧を表示します。

    def _init_helpText(self, subject, frame, font, file):
        parent = ScrollableText(frame, font)
        parent.frame.grid(row=1, column=0, sticky=NSEW)
        text = parent.text
        text.config(wrap=CHAR)
        self.help_file_write(subject, name=file)
        self.help_file_read(name=file, text=text)
        return text

_init_helpText は、下段のテキスト領域を初期設定します。

    ...
    def help_file_write(self, subject, name):
        sys.stdout = file(name, "w")
        help(subject)

help_file_write は、help の出力結果を、作業用ファイルに残します。

    def help_file_read(self, name, text):
        for e in file(name, "r"):
            text.insert(END, e)

help_file_read は、作業用ファイルから1行ずつ読み込んで、それをテキスト領域に追加表示します。

Last updated♪2009/08/13