gpt4 book ai didi

python - 在 Pynput 中检索用于单击和释放的 x 和 y 鼠标位置

转载 作者:行者123 更新时间:2023-12-04 17:13:24 24 4
gpt4 key购买 nike

我正在使用带有 pynput 的 Python 3.9.7,我想检索单击和释放鼠标的 x 和 y 位置 单独并将其保存到函数 on_click 之外的变量中(例如:按下时 px = x 位置,释放时 rx = x 位置)以供其他函数使用
代码如下,代码修改自Pynput documentations :

from pynput import mouse
import time

px = 0
py = 0
rx = 0
ry = 0

pressed_location = 0, 0
released_location = 0, 0

def on_click(x, y, button, pressed):
global pressed_location
global released_location
global px,py,rx,ry

if pressed:
pressed_location = x, y
px = x
py = y
else:
released_location = x, y
rx = x
ry = y
#debugging inside functions
#print('You pressed at {0}x{1} and released at {2}x{3}'.format(*pressed_location, *released_location))
print('Inside function pressed at {0}x{1}'.format(*pressed_location, *released_location))
print('Inside function released at {2}x{3}'.format(*pressed_location, *released_location))
return False

listener = mouse.Listener(on_click=on_click)
listener.start()

#debugging outside functions
print ("Outside function pressed: ", px , "x" ,py)
print ("Outside function released: ", rx , "x" , ry)
但是,我对输出感到困惑(在函数之外,因为它仍然显示为 0,而函数内部的变量显示的是实际值。)示例结果如下:
我只是希望函数内部变量的值可以“转移”到函数外部的变量中。提前致谢。
Outside function pressed:  0 x 0
Outside function released: 0 x 0
>>> Inside function pressed at 293x249
Inside function released at 768x815
rr

最佳答案

可能有更好的方法,但这有效:

from pynput import mouse
import time

pressed_location = 0, 0
released_location = 0, 0

def on_click(x, y, button, pressed):
global pressed_location
global released_location
if pressed:
pressed_location = x, y
else:
released_location = x, y
print('You pressed at {0}x{1} and released at {2}x{3}'.format(*pressed_location, *released_location))

listener = mouse.Listener(on_click=on_click)
listener.start()

while True:
time.sleep(1)
我创建了一个全局变量 pressed_location ,我们给它一个默认值。如果用户按下鼠标,位置就会存储在那里。如果用户释放鼠标,我们会显示按下的位置和释放的位置。
示例输出:
You pressed at 103x412 and released at 299x559
You pressed at 207x478 and released at 207x478
在上面的第一个事件中,我在按下后移动了鼠标。在第二个事件中,我只是点击了。

关于python - 在 Pynput 中检索用于单击和释放的 x 和 y 鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69077267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com