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, which is done like this:
x = canvas.canvasx(event.x)
A string of the form “ @ x , y ”, to return the character of the character containing canvas coordinates ( x , y ) . If those coordinates are above or to the left of the text item, the method returns 0; if the coordinates are to the right of or below the item, the method returns the index of the end of the item.
The Canvas widget supplies graphics facilities for Tkinter. Among these graphical objects are lines, circles, images, and even other widgets. With this widget it's possible to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.
A tkinter canvas can be used to draw in a window. Use this widget to draw graphs or plots. You can even use it to create graphical editors. You can draw several widgets in the canvas: arc bitmap, images, lines, rectangles, text, pieslices, ovals, polygons, ovals, polygons, and rectangles.
Tkinter Canvas widget can be used for multiple purposes such as drawing shapes, objects, creating graphics and images. To draw a line on a Canvas, we can use create_line(x,y,x1,y1, **options) method. In Tkinter, we can draw two types of lines: simple and dashed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With