How to get mouse position relative to parent widget in tkinter?

I need to get the mouse position relative to the tkinter window.

+4
source share
2 answers

In general, you do not need to β€œreceive” this information because it is provided to you as part of the event object that is being transmitted. You probably need this information only when responding to an event, and the event gives you this Information.

Place it more succinctly to get the information you just need to extract from the event object.

Here is an example:

import Tkinter class App: def __init__(self, root): f = Tkinter.Frame(width=100, height=100, background="bisque") f.pack(padx=100, pady=100) f.bind("<1>", self.OnMouseDown) def OnMouseDown(self, event): print "frame coordinates: %s/%s" % (event.x, event.y) print "root coordinates: %s/%s" % (event.x_root, event.y_root) root=Tkinter.Tk() app = App(root) root.mainloop() 
+5
source

Get the screen coordinates of the mouse move event ( x / y_root ) and subtract the screen coordinates of the window ( window.winfo_rootx() / y() ).

+2
source

Source: https://habr.com/ru/post/1316255/


All Articles