jb3 Hd
jb3 Hd

Reputation: 155

How to display canvas coordinates when hovering cursor over canvas?

When I hover over the canvas I want some labels on top of the canvas to display x,y coordinates which stay the same if I keep my cursor still but change when I move it. How would I do this?

Upvotes: 2

Views: 5223

Answers (2)

FooBar167
FooBar167

Reputation: 2901

Also use <Enter> event. So when you switch between windows (<Alt>+<Tab> hotkey), your cursor will show the correct coordinates.

For example, you put your cursor on the canvas and <Motion> event will track it, but when you press <Alt>+<Tab> and switch to another window, then move your cursor a bit and <Alt>+<Tab> on your canvas again -- coordinates of the your cursor will be wrong, because <Motion> event doesn't track switches between windows. To fix it use <Enter> event.

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

def get_coordinates(event):
    canvas.itemconfigure(tag, text='({x}, {y})'.format(x=event.x, y=event.y))

canvas.bind('<Motion>', get_coordinates)
canvas.bind('<Enter>', get_coordinates)  # handle <Alt>+<Tab> switches between windows
tag = canvas.create_text(10, 10, text='', anchor='nw')

root.mainloop()

Upvotes: 2

tobias_k
tobias_k

Reputation: 82889

You can use a callback method and bind it to a Motion event.

import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

def moved(event):
    canvas.itemconfigure(tag, text="(%r, %r)" % (event.x, event.y))

canvas.bind("<Motion>", moved)
tag = canvas.create_text(10, 10, text="", anchor="nw")  

root.mainloop()

Upvotes: 5

Related Questions