Python.use(better,Tkinter)《21》create_rectangle

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

Python.use(better, Tkinter)
create_rectangle《Python3.1》

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

概要

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

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

〓 create_rectangle

図形を描画する

次のコードを実行すると、ウィンドウが現われます。

>>> ex_create_rectangle1()


  • 左側には、中空の図形が描かれます。
  • 中央には、内部を塗り潰した図形(赤色)が描かれます。
  • 右側には、輪郭を強調した図形(青色/幅3画素)が描かれます。
def ex_create_rectangle1():
    root = Tk(); root.title("create_rectangle")
    w = Canvas(width=300, height=120)
    w.pack()

    box = 10, 10, 100, 100
    w.create_rectangle(box)
    box = 110, 10, 200, 100
    w.create_rectangle(box, fill="red")
    box = 210, 10, 300, 100
    w.create_rectangle(box, fill="yellow", outline="blue", width=3)

    root.mainloop()

《Note》class Canvas(Widget): # /Python-3.0/Lib/tkinter/__init__.py

    def create_rectangle(self, *args, **kw):
        """Create rectangle with coordinates x1,y1,x2,y2."""
  • 指定した領域に「矩形」を生成して、その識別情報を与えます。引数 *args には、図形を描画する矩形領域を表わす、2点 (x1,y1) および (x2,y2) の座標を指定します。引数 **kw には、任意のオプションを指定できます。
keyword arguments
fill= 図形の内部を塗るときの色(規定値は 'black')を指定します
outline= 図形の輪郭を描くときの色(規定値は 'black')を指定します
width= 図形の輪郭を描くときの幅(画素数:規定値は 1)を指定します
図形を操作する

次のコードを実行すると、ウィンドウが現われます。

>>> ex_create_rectangle2()


  • 左側のボタン〔del〕を選択すると、左側の図形が削除されます。
  • 中央のボタン〔conf〕を選択すると、中央の図形の色が変化します。
  • 右側のボタン〔coords〕を選択すると、右側の図形の形が変化します。
def ex_create_rectangle2():
    root = Tk(); root.title("create_rectangle")
    w = Canvas(width=200, height=50)
    w.pack()

    box = 10, 10, 50, 50
    item1 = w.create_rectangle(box, fill="red")
    box = 60, 10, 100, 50
    item2 = w.create_rectangle(box, fill="green")
    box = 110, 10, 150, 50
    item3 = w.create_rectangle(box, fill="blue")

    b = Button(root, text="del",
        command=lambda: w.delete(item1))
    b.pack(side=LEFT)
    
    b = Button(root, text="conf",
        command=lambda: w.itemconfigure(
            item2, fill="yellow", outline="red", width=3))
    b.pack(side=LEFT)
    
    b = Button(root, text="coords",
        command=lambda: w.coords(
            item3, 120, 20, 150, 50))
    b.pack(side=LEFT)

    root.mainloop()

《Note》class Canvas(Widget): # /Python-3.0/Lib/tkinter/__init__.py

    def delete(self, *args):
  • 指定した図形 *args を削除します。
    def itemconfigure(self, tagOrId, cnf=None, **kw):
  • 指定した図形 tagOrId の属性値を、任意のオブション **kw で更新します。指定したキーワード引数 fill/outline/width は、図形を生成するときに指定したオブションと同じものです。
    def coords(self, *args):
  • 指定した座標 *args で値を更新して、図形を変形します。

Last updated♪2009/09/01