Python.use(better,Tkinter)《余録》itemconfigure(anchor=)

記事一覧

Python.use(better, Tkinter)
itemconfigure(anchor=) 《Python3.1》

《著》森こねこ・小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪1993/11/25

概要

キャンバスにテキストを描く方法を紹介します。

Tkinter によるオブジェクト指向プログラミングへの扉を開きます。
※ Tcl/Tk で作成した例題を、Tkinter で再構成しました。

itemconfigure

テキストを配置する
>>> ex_itemconfig_anchor()
center: (12, 26, 188, 74)
n: (85, 50, 116, 98)
sw: (99, 2, 159, 50)
メニュー項目を選択すると、テキストの配置が変わります。赤色で描かれた anchor を基点にして、テキストを描画します。
メニュー項目〔center〕を選択すると、anchor(赤色)を基点にして(anchor の位置が「中央」になる)テキストを描画します。
メニュー項目〔n〕を選択すると、anchor(赤色)を基点にして(anchor の位置が「北(上)」になる)テキストを描画します。
メニュー項目〔sw〕を選択すると、anchor(赤色)を基点にして(anchor の位置が「南西(左下)」になる)テキストを描画します。
def ex_itemconfig_anchor():   # canvas.itemconfig(anchor=)

    class TIPS(object):
        def __init__(self, master, canvas):
            self.value = StringVar()
            self.master = master
            self.canvas = canvas
            self.tag = self.create_text()
            self.create_menubutton()

        def create_text(self):
            point=(100,50); anchor=CENTER
            tag = self.canvas.create_text(
                point,
                text=anchor, anchor=anchor, font="courier 48",
                )
            self.canvas.create_rectangle(
                point, point,
                width=2, outline="red",
                )
            self.canvas.tag_bind(
                tag,
                sequence='',
                func=self.clickhandler,
                )
            return tag
        
        def clickhandler(self, event):
            text = canvas.itemconfig(self.tag, "text")
            box = canvas.bbox(self.tag)
            print("%s: %s"%(text[-1], box))

        def create_menubutton(self):
            widget = Menubutton(
                master=self.master,
                text='anchor',
                )
            widget.pack()

            menu = Menu(widget)
            widget['menu'] = menu

            s = N, NE, E, SE, S, SW, W, NW, CENTER,
            for e in s:
                menu.add_radiobutton(
                    label=e,
                    value=e,
                    variable=self.value,
                    command=self,
                    )

        def __call__(self):
            s = self.value.get()
            self.canvas.itemconfig(
                self.tag,
                text=s,
                anchor=s,
                )

    ## ----------------------------------------
    root = Tk()
    root.title("Button(compound=)")
    root.config(padx=8, pady=8)

    canvas = Canvas(
        master=root,
        width=200, height=100, bg="Yellow",
        relief=RIDGE, borderwidth=5,
        )
    canvas.pack()

    tips = TIPS(root, canvas)

    root.mainloop()

コードの解説

《Note》

class Canvas(Widget):         # /Python-3.0/Lib/tkinter/__init__.py
    def itemconfigure(self, tagOrId, cnf=None, **kw):
    itemconfig = itemconfigure
  • 各項目を再構成して、その結果を再描画します。
keyword arguments
tagOrId タグ名(str)/識別子(int)を指定します


関連記事

Last updated♪2009/09/24