问题
my dear py-experts. I wrote a GUI program in python (Tkinter library) which displays a picture, to display an image i used the Canvas widget. The program does load a picture (its width/height always bigger than Canvas width/height) and when i make a mouse click on the Canvas it returns a x,y - coordinates (and color grayscale value), but it always a coordinates of Canvas, not an image ones. For example - image sizes are x=5040 and y=3360 and Canvas widget sizes are x=500 and y=400 and when i making a click on Canvas i never get values,even if i scrolling image, more than 500 for X-axis and 400 for Y-axis respectively. What i did wrong, how to get right information from the image? Thnx.
回答1:
As the docs on Canvas explain:
Coordinate Systems
The
Canvas
widget uses two coordinate systems; the window coordinate system (with (0, 0) in the upper left corner), and a canvas coordinate system which specify where the items are drawn. By scrolling the canvas, you can specify which part of the canvas coordinate system to show in the window.The scrollregion option is used to limit scrolling operations for the canvas. To set this, you can usually use something like:
canvas.config(scrollregion=canvas.bbox(ALL))
To convert from window coordinates to canvas coordinates, use the canvasx and canvasy methods:
def callback(event):
canvas = event.widget
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
print canvas.find_closest(x, y)
Note that this will give you canvas coordinates, which are not necessarily the same as image coordinate—if you, e.g., left a border around the image within the canvas, you will have to correct for that manually.
来源:https://stackoverflow.com/questions/24895655/is-there-way-to-return-actual-x-y-coordinates-from-the-image