'Mouse position using python
I have written the following two scripts to show the current mouse position in the console:
Using tkinter
:
import tkinter
import time
print('Press Ctrl-C to quit.')
p=tkinter.Tk()
try:
while True:
x, y = p.winfo_pointerxy()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)
time.sleep(1)
except KeyboardInterrupt:
print('\n')
1535, 863
Using pyautogui
import pyautogui, sys
import time
print('Press Ctrl-C to quit.')
try:
while True:
x, y = pyautogui.position()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)
time.sleep(1)
except KeyboardInterrupt:
print('\n')
1919, 1079
Why these two are different? What is the difference between pyautogui.position()
and tkinter.winfo_pointerxy()
?
The referred question in comment doesn't answer my question because I want to know the difference between the two functions and how to get similar output.
Solution 1:[1]
As Stated In The Original Documentation Of Both Libraries
w.winfo_pointerxy():
Returns a tuple (x, y) containing the coordinates of the mouse pointer relative to w's root window.
Tkinter Documentation
While pyautogui.position()
gives with respect to the left top corner of your screen.
PyAutoGUI Documentation
Use This x = p.winfo_pointerx() - p.winfo_rootx()
y = p.winfo_pointery() - p.winfo_rooty()
To Know More Getting the absolute position of cursor in tkinter
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |