Python.use(better,Tkinter)《27》create_text

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

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

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

■ 概要

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

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

■ 関連記事

前の記事次の記事

create_text

■ テキストを配置する

  • 赤色で描かれた anchor を基点にして、テキストを描画します。
    root = Tk(); root.title("create_text")
    w = Canvas(width=260, height=240)
    w.pack()
    d0 = 10; d1 = 35; d2 = d1*2; n = 3
    R = range(d0, d0+d2*n+1, d0+d2)
    points = [(x, y) for x in R for y in R]
    compass = NW, W, SW, N, CENTER, S, NE, E, SE
    for (x, y), anchor in zip(points, compass):
        coordinates = x, y, x+d2, y+d2
        w.create_rectangle(coordinates)
        p = x+d1, y+d1
        w.create_text(
            p, text=anchor, font="courier 18", anchor=anchor)
        w.create_rectangle(p, p, outline="red", width=2)
    root.mainloop()

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

    def create_text(self, *args, **kw):
        """Create text with coordinates x1,y1."""
  • 指定した位置に「テキスト」を生成して、その識別情報を与えます。
keyword arguments
text= テキスト表示させたい文字列を指定します
font= フォント情報を指定します
anchor= テキストを描く位置 CENTER(中央:規定値)N(北)NE(北東)E(東)SE(南東)S(南)SW(南西)W(西)NW(北西)を指定します。anchor で指定した方向に基点 p(x0,y0) が位置するように、テキストを描画します
■ テキストの色を指定する


  • 左から右へと順に、赤、緑、青のテキストが描かれます。
  • 右端には、袋文字を模したテキストが描かれます。上下左右斜め方向に1画素ずつずらしてテキスト(赤)を描いた後で、最後に中央にテキスト(黄)を描きます。すると、赤で縁取られた黄色のテキスト(袋文字)が描かれます。
    root = Tk(); root.title("create_text")
    w = Canvas(width=270, height=60)
    w.pack()
    f1, f2 = "courier 12", "courier 24"
    constants = "red", "green", "blue"
    for i, c in enumerate(constants):
        x, y = 10+60*i, 10
        coordinates = x, y, x+50, y+50
        w.create_rectangle(coordinates)
        p = x+2, y+20
        w.create_text(p, text=c, font=f1, anchor=NW, fill=c)
        w.create_rectangle(p, p, width=2)
    R = range(3)
    px, py = 225, 20
    s = "Happy"
    for x, y in [(x, y) for x in R for y in R]:
        p = px+x, py+y
        w.create_text(p, text=s, font=f2, fill="red")
    p = px+1, py+1
    w.create_text(p, text=s, font=f2, fill="yellow")
    root.mainloop()

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

    def create_text(self, *args, **kw):
        """Create text with coordinates x1,y1."""
  • 指定した位置に「テキスト」を生成して、その識別情報を与えます。
fill= テキストを描くときの色を指定します

Last updated♪2009/08/17