Yngve
Yngve

Reputation: 783

Python, Tkinter: How to get coordinates on scrollable canvas

I have a Tkinter canvas with a scrollbar, and some items that when I click them, it's supposed to return the coordinates. (Using Python.)

This works fine with the objects that's initially visible in the window. When I scroll down, however, and the items further down on the canvas come into view, I don't get their canvas coordinates when clicking, but the window coordinates.

I can't find info on how to get the absolute coordinates, so I'm wondering if anyone here knows how to do it?

Thanks.

Upvotes: 10

Views: 7493

Answers (1)

gary
gary

Reputation: 4255

Check out the documentation for the canvas widget here.

To convert from window coordinates to canvas coordinates, use the canvasx and canvasy methods.

Here is an example callback function which converts the window's x and y coordinates and prints the item closest to that position via the find_closest() method.

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

Upvotes: 15

Related Questions