目次
python canvas のメソッド
Python で GUI を作るときによく使われる tkinter.Canvas
のメソッドを以下にまとめます。Canvas
は図形描画、画像表示、マウスイベントなどに使われます。
🔧 基本メソッド一覧(tkinter.Canvas
)
🖼 キャンバスの作成
canvas = tk.Canvas(master, width=300, height=200, bg="white") canvas.pack()
✏️ 描画系メソッド
メソッド | 説明 |
---|---|
create_line(x1, y1, x2, y2, ..., options) | 線を描く(複数点対応) |
create_rectangle(x1, y1, x2, y2, options) | 長方形を描く |
create_oval(x1, y1, x2, y2, options) | 楕円を描く(外接する矩形指定) |
create_arc(x1, y1, x2, y2, options) | 円弧を描く(start=角度, extent=角度) |
create_polygon(x1, y1, x2, y2, ..., options) | 多角形を描く |
create_text(x, y, text="...", options) | テキストを描画 |
create_image(x, y, image=ImageTk.PhotoImage) | 画像を表示(Pillowなどで読み込んだ画像) |
🧩 操作系メソッド
メソッド | 説明 |
---|---|
coords(id, new_coords) | オブジェクトの座標を取得/変更 |
itemconfig(id, options) | オブジェクトの設定を変更 |
delete(id or "all") | オブジェクトを削除 |
move(id, dx, dy) | オブジェクトを移動 |
scale(id, x_origin, y_origin, x_scale, y_scale) | 拡大・縮小 |
tag_bind(tagOrId, "<Event>", callback) | オブジェクトにイベントをバインド |
find_withtag("tag") | タグでオブジェクトを検索 |
itemcget(id, option) | オプション値の取得 |
🎯 ユーティリティ
メソッド | 説明 |
---|---|
canvasx(x) / canvasy(y) | スクロール位置を考慮した座標取得 |
create_window(x, y, window=widget) | キャンバス上に別のウィジェットを表示 |
bbox(id) | オブジェクトのバウンディングボックスを取得 |
gettags(id) | タグ一覧を取得 |
✅ 使用例(簡単な図形)
import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, width=400, height=300, bg="white") canvas.pack() # 図形描画 canvas.create_rectangle(50, 50, 150, 100, fill="lightblue") canvas.create_line(0, 0, 200, 150, fill="red", width=2) canvas.create_text(200, 200, text="Hello, Canvas!", font=("Arial", 16)) root.mainloop()
必要なら特定の機能(たとえばマウスイベントやドラッグ処理、画像表示など)にフォーカスした例も用意できますよ!何かやりたいことがあれば教えてください。