Is there a way to convert canvas coordinates to window coordinates in Tkinter?
It would be the opposite of converting from window to canvas coordinate, wich is done like this:
x = canvas.canvasx(event.x)
Is there a way to convert canvas coordinates to window coordinates in Tkinter?
It would be the opposite of converting from window to canvas coordinate, wich is done like this:
x = canvas.canvasx(event.x)
Use the canvasx
and canvasy
methods, giving an argument of zero, to compute the x/y of the upper left corner of the visible canvas. Then just use math to convert the canvas coordinate to something relative to the window.
# upper left corner of the visible region
x0 = self.canvas.canvasx(0)
y0 = self.canvas.canvasy(0)
# given a canvas coordinate cx/cy, convert it to window coordinates:
wx0 = cx-x0
wy0 = cy-y0
For example, if the canvas is scrolled all the way to the top and left, x0 and y0 will be zero. Any canvas coordinate you give will be the same as the window coordinate (ie: canvas x/y of 0,0 will correspond to window coordinate 0,0).
If you've scrolled 100 pixels down and to the right, a canvas coordinate of 100,100 will translate to a window coordinate of 0,0 since that is the pixel that is in the upper left corner of the window.
This gives you a value relative to the upper left corner of the canvas. If you need this relative to the upper left corner of the whole window, use winfo_x
and winfo_y
to get the coordinate of the canvas relative to the window and do a little more math. Or, use winfo_rootx
and winfo_rooty
to get the coordinates of the widget relative to the screen.