我正在使用Python 3.9.7和pynput,想要分别检索鼠标点击和释放时的x和y位置,并将其保存到函数on_click之外的变量中(例如:px =按下时的x位置,rx =释放时的x位置),以供其他函数使用。
以下是代码,代码已经根据Pynput文档进行了修改:
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
def
之前定义一些全局变量,然后使用 if else 语句代替 format,所以如果pressed
,则可以将你的 mx 值设置为它,否则将其设置为你的 mrx 值。 - iѕєρєня