Python tkinter GUIプログラミング アウトライン

 今日も見に来てくださって、ありがとうございます。石川さんです。

 GUIのエディターを作ったときに、アウトラインを表示する方法をちょっと検討してみました。キャンバスの中にcreate_window()でキャンバスを作成して、同じ内容を描画する、というのでどうかなぁ、ということで、ちょっとお試ししてみました。

できあがりイメージ

右下にアウトライン(鳥瞰図)表示

 クリックした個所に四角形を描画します。描画と同時に右下のアウトラインにも描画します。

ソースコード

 ソースコードは以下の通りです。

import tkinter as tk

class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Canvas outline sample")
        self.outline = None
        self.outline_item = None
        
        self.canvas = tk.Canvas(self, background="white")
        self.canvas.pack(fill=tk.BOTH,expand=True)
        self.canvas.bind("<1>",self.update_outline)
        self.canvas.bind("<Configure>",self.update_outline)

    def update_outline(self, event):
        if self.outline == None or self.outline_item == None:
            self.outline = o = tk.Canvas(self, background="lightblue")
            c = self.canvas
            width, height = c.winfo_width(), c.winfo_height()
            w, h = width//5, height//5
            x, y = width - w//2, height - h//2
            self.outline_item = c.create_window(x, y, width=w, height=h, window=o)
            return

        if event.type == tk.EventType.Configure:
            c = self.canvas
            width, height = c.winfo_width(), c.winfo_height()
            w, h = width//5, height//5
            x, y = width - w//2, height - h//2
            oi = self.outline_item
            x0, y0 = c.coords(oi)
            dx = x - x0
            dy = y - y0
            c.move(oi,dx,dy)
            c.itemconfigure(oi,width=w,height=h)

        elif event.type == tk.EventType.Button:
            c = self.canvas
            x, y = event.x, event.y
            c.create_rectangle(x, y, x+100, y+100)
            o = self.outline
            o.create_rectangle(x//5,y//5,(x+100)//5,(y+100)//5)
    
if __name__ == "__main__":
    application = Application()
    application.mainloop()

 ウィンドウのサイズを変更したら、アウトラインのサイズも変更されます。

まとめ

 今回は、クリックしたときに同時に小さいサイズの描画をしました。実際のGUIエディターでは、アウトラインの表示、非表示の切り替えができるようにする必要がありそうですね。スクロールとか、拡大縮小も対応しなければいけないでしょうね。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


The reCAPTCHA verification period has expired. Please reload the page.