0

I have a Tkinter canvas widget and I'd like to create a stipple pattern on it. I know I could do it manually using the create_line method. However, I'd think there would seem to be a better way. Any help would be much appreciated.

What I'm currently working with. (press Alt-F4 to exit the program)

import Tkinter, re

class StippleCanvas(Tkinter.Tk):
    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)


        self.overrideredirect(1)
        self.resizable(False,False)
        self.wm_attributes("-topmost", 1)
        self.attributes("-alpha", 0.9)

        w = 90
        h = 90

        self.Ca = Tkinter.Canvas(self, width=w, height=h, highlightthickness=0, bd=0, bg='grey25')
        self.Ca.grid(column=0, row=0)
        self.bind('<Button-1>', self.relative_mouse_position)
        self.bind('<ButtonRelease-1>', self.wid_unbind)

        i0 = 0
        while i0 < w:
            i1 = 0
            while i1 < h:
                self.Ca.create_line(i1, i0, i1+1, i0, fill='grey20', width=1)
                i1 = i1 + 2
            i0 = i0 + 2

    def geom_grab (self):
        Cursorgfltr = re.compile(r"(\d+), (\d+)")
        CursorPos = self.winfo_pointerxy()
        CursorPosGr = Cursorgfltr.search(str(CursorPos))
        self.CursorX = int(CursorPosGr.group(1))
        self.CursorY = int(CursorPosGr.group(2))

        gfltr = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")

        gf = gfltr.search(self.wm_geometry())
        self.X = int(gf.group(4))
        self.Y = int(gf.group(6))

    def relative_mouse_position (self, event):
        self.geom_grab()

        RelX = self.CursorX - self.X
        RelY = self.CursorY - self.Y

        self.Ca.bind( "<Motion>", lambda event: self.wid_drag(event, RelX, RelY) )

    def wid_drag (self, event, RelX, RelY):


        self.geom_grab()

        X = self.CursorX - RelX
        Y = self.CursorY - RelY

        if X < 0:
            X = 0

        if Y < 0:
            Y = 0

        self.wm_geometry('+' + str(X) + '+' + str(Y))


    def wid_unbind (self, event):
        self.Ca.unbind("<Motion>")

def run():
    StippleCanvas(None).mainloop()
if __name__ == '__main__':
    run()
4

1 に答える 1

0

もっとも単純な?それはあなたの「シンプル」の定義に依存します。1つの方法は、描画プログラムを使用して背景に必要な画像を作成し、それをキャンバスに配置することです。これは、事前にキャンバスのサイズを知っていることを前提としています。キャンバスに単一の画像を挿入することほど簡単なことはありません。

このテーマのバリエーションは、小さなタイルを作成し、tkinterの画像処理を使用して、元の画像を新しい画像に並べて、適切なサイズの新しい画像を作成することです。これは、キャンバスのサイズが変更されるたびに実行できます。この例のいくつかは、PythonではなくTclにありますが、次のリンクで見ることができます(Pythonへの変換は非常に簡単なので、気にしないでください)。

http://wiki.tcl.tk/4389

とはいえ、率直に言って、単純な点刻では、あなたがしたことは問題ありません。点刻描画を関数に移動して、キャンバスのサイズが変更されたとき(つまり、<Configure>イベントを取得したとき)に再実行できるようにします。

于 2011-01-29T23:36:05.667 に答える