Widget Canvas มีระบบพิกัด 2 ระบบ: (ก) ระบบพิกัดหน้าต่าง (Window coordinate system) และ (ข) ระบบพิกัด Canvas (canvas coordinate system) ระบบพิกัดหน้าต่างเริ่มต้นจากมุมซ้ายบน (0,0) ในหน้าต่าง ส่วนระบบพิกัด Canvas ระบุว่าตัวอย่างวางไว้ที่ไหนใน Canvas จริงๆ
เพื่อแปลงระบบพิกัดหน้าต่างเป็นระบบพิกัด Canvas ให้ใช้เมธอด 2 ตัว:
canvasx(event.x) canvasy(event.y)
หากพิจารณากรณีระบบพิกัดหน้าต่าง เหตุการณ์เมาส์เกิดขึ้นเฉพาะในระบบพิกัดหน้าต่าง สามารถแปลงพิกัดหน้าต่างเป็นพิกัด Canvas ได้
ตัวอย่าง
ในแอปพลิเคชันนี้ จะหาตำแหน่งของเมาส์ภายใน Canvas widget
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Create a canvas widget
canvas = Canvas(win)
canvas.pack()
def on_button_pressed(event):
start_x = canvas.canvasx(event.x)
start_y = canvas.canvasy(event.y)
print("start_x, start_y =", start_x, start_y)
def on_button_motion(event):
end_x = canvas.canvasx(event.x)
end_y = canvas.canvasy(event.y)
print("end_x, end_y=", end_x, end_y)
# Bind the canvas with Mouse buttons
canvas.bind("", on_button_pressed)
canvas.bind("", on_button_motion)
# Add a Label widget in the window
Label(win, text="Move the Mouse Pointer and click " "anywhere on the Canvas").pack()
win.mainloop() ผลลัพธ์
การรันโค้ดจะแสดงหน้าต่าง

หากเลื่อนเมาส์และคลิกที่ใดก็ตามบน Canvas จะพิมพ์พิกัดสัมพัทธ์ของพอยน์เตอร์บนคอนโซล
start_x, start_y = 340.0 159.0