I need to get the mouse position relative to the tkinter window.
Asked
Active
Viewed 9,730 times
2 Answers
6
Generally speaking you should never need to "get" this information because it is given to you as part of the event object that is passed in. You probably only need this information when responding to an event, and the event gives you this information.
Put more succinctly, to get the information you simply have to retrieve it from the event object.
Here's 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()

Bryan Oakley
- 370,779
- 53
- 539
- 685
-
5I don't agree that you shouldn't generally need this information. I'm writing a quick app now to do photo editing...I absolutely need the relative rather than absolute position of the mouse click since it's position relative to the displayed image, not relative to the screen, that matters. I'm sure your position is often correct, but there are legit uses for relative position, lots of legit uses. – sunny Sep 02 '15 at 19:46
-
@sunny: but aren't you only needing that information when processing an event? The information is definitely useful, it's just that you normally don't need to _get_ it because it's _given_ to you in the event handler. – Bryan Oakley Sep 02 '15 at 20:09
-
1yes, so we agree the information is useful? I thought you were saying it was not useful info. – sunny Sep 02 '15 at 20:28
-
@sunny: I never said you don't need the information, I said you _don't need to **get** the information_. The information is definitely useful, but it's part of the event object that is passed in, so you don't need to query tkinter for the information because you already have it. – Bryan Oakley Sep 02 '15 at 21:43
-
You're right. I missed the nuance in what you were saying. – sunny Sep 02 '15 at 21:49
3
Get the screen coordinates of the mouse move event (x
/y_root
) and subtract the screen coordinates of the window (window.winfo_rootx()
/y()
).

Aaron Digulla
- 321,842
- 108
- 597
- 820