For duplicate-markers: I am fully aware that there are some similar questions in matplotlib
, such as this one. My question is about
What you seem to be asking for is a 2D World to Viewport Transformation:
Take an area defined in "world coordinates" (say 10 metres by 10 metres) and map it to an area defined in canvas coordinates.
eg.
from tkinter import *
xmin,ymin,xmax,ymax = 0,0,10,10 # world
umin,vmin,umax,vmax = 0,480,640,0 # viewport (note: y reversed)
points = [(2,2), (4,4), (7,7), (8,8)] # some "world" points
def world_to_viewport(worldpoint):
x,y = worldpoint
u = (x - xmin)*((umax - umin)/(xmax - xmin)) + umin
v = (y - ymin)*((vmax - vmin)/(ymax - ymin)) + vmin
return u,v
def pixel_to_world(pixel):
u,v = pixel
x = (u - umin)*((xmax - xmin)/(umax - umin)) + xmin
y = (v - vmin)*((ymax - ymin)/(vmax - vmin)) + ymin
return x,y
root = Tk()
canvas = Canvas(root, width=640, height=480, bd=0, highlightthickness=0)
canvas.pack()
def on_click(event):
root.title('%s,%s' %(pixel_to_world((event.x,event.y))))
canvas.bind('', on_click)
r = 5
for point in points:
cx,cy = world_to_viewport(point)
canvas.create_oval(cx-r,cy-r,cx+r,cy+r,fill='red')
root.mainloop()