Is there a way to get the position of the mouse and set it as a var?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could set up a callback to react to <Motion> events:
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop()
I’m not sure what kind of variable you want. Above, I set local variables x and y to the mouse coordinates.
If you make motion a class method, then you could set instance attributes self.x and self.y to the mouse coordinates, which could then be accessible from other class methods.
Method 2
At any point in time you can use the method winfo_pointerx and winfo_pointery to get the x,y coordinates relative to the root window. To convert that to absolute screen coordinates you can get the winfo_pointerx or winfo_pointery, and from that subtract the respective winfo_rootx or winfo_rooty
For example:
root = tk.Tk() ... x = root.winfo_pointerx() y = root.winfo_pointery() abs_coord_x = root.winfo_pointerx() - root.winfo_rootx() abs_coord_y = root.winfo_pointery() - root.winfo_rooty()
Method 3
Personally, I prefer to use pyautogui, even in combination with Tkinter. It is not limited to Tkinter app, but works on the whole screen, even on dual screen configuration.
import pyautogui
x, y = pyautogui.position()
In case you want to save various positions, add an on-click event.
I know original question is about Tkinter.
Method 4
I would like to improve Bryan’s answer, as that only works if you have 1 monitor, but if you have multiple monitors, it will always use your coordinates relative to your main monitor. in order to find it relative to both monitors, and get the accurate position, then use vroot, instead of root, like this
root = tk.Tk() ... x = root.winfo_pointerx() y = root.winfo_pointery() abs_coord_x = root.winfo_pointerx() - root.winfo_vrootx() abs_coord_y = root.winfo_pointery() - root.winfo_vrooty()
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0