Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Tkinter canvas coordinate to window?

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)
like image 806
Marcos Saito Avatar asked Oct 18 '11 17:10

Marcos Saito


People also ask

What does canvas Coords return?

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.

Is canvas a widget in tkinter?

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.

How does tkinter canvas work?

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.

Can you draw in tkinter?

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.


1 Answers

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.

like image 129
Bryan Oakley Avatar answered Nov 03 '22 16:11

Bryan Oakley