简体   繁体   中英

Python - Finding Difference Between Two Mouse Positions

I am trying to find the differences between two mouse positions. Although, I cant figure it out, I am a beginner and was wondering if anyone can help me out.

I am trying to make a program that prints out how far you've moved your mouse in x amount of time. This is the only part I cant figure out.

from tkinter import *
import time

time.sleep(1)
x = (pyautogui.position())

time.sleep(1)
y = (pyautogui.position())

p = x - y
print(p)

I expected it to print out the difference but it gives me an error.

TypeError: unsupported operand type(s) for -: 'Point' and 'Point'

Please take a look at the documentation . You have to store the coordinates in two objects if you want to get separate coordinates:

x, y = pyautogui.position()

Now you can get the distance vector with simple arithmetics:

time.sleep(1)
x0, y0 = (pyautogui.position())

time.sleep(1)
x1, y1 = (pyautogui.position())

Distance_X = x1 - x0
Distance_Y = y1 - y0

Otherwise, you have to use the x or y member of the Point object.

time.sleep(1)
P0 = (pyautogui.position())

time.sleep(1)
P1 = (pyautogui.position())

Distanxe_X = P1.x - P0.x
Distance_Y = P1.y - P0.y

The pyautogui returns a Point which is a 2-D coordinate of the form (x,y)

You need to use the Distance Formula to compute the Distance between any two points

Working example below

import time
import pyautogui
import math

time.sleep(1)
x = (pyautogui.position())

time.sleep(1)
y = (pyautogui.position())

dist = math.sqrt((y.x - x.x)**2 + (y.y - x.y)**2)

print(round(dist, 2))

Also, pyautogui is not a part of the tkinter module in Python 3. So I have installed and imported it separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM