Python Tkinter converts canvas coordinate to window coordinate

Is there a way to convert canvas coordinates to window coordinates in Tkinter?

This would be the inverse transformation from the window to the canvas coordinate, which is done as follows:

x = canvas.canvasx(event.x) 

Thanks in advance.

+4
source share
1 answer

Use the canvasx and canvasy , giving a zero argument to calculate x / y of the upper left corner of the visible canvas. Then just use the math to transform the coordinates of the canvas into 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 scrolls to the very top and to the left, x0 and y0 will be zero. Any coordinate of the canvas will be the same as the coordinate of the window (i.e., the canvas x / y 0,0 will correspond to the coordinate of the window 0,0).

If you scrolled 100 pixels down and to the right, the canvas coordinate 100 100 will be transferred to the window coordinate 0,0, since this 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 canvas coordinate relative to the window and do a little more math. Or use winfo_rootx and winfo_rooty to get the widget coordinates relative to the screen.

+6
source

All Articles