【发布时间】:2021-11-03 16:54:30
【问题描述】:
我正在使用 Python 3.9.7 和 pynput,我想检索鼠标单击和释放的 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
【问题讨论】:
-
在
def之前定义一些全局变量,然后使用 if else 语句代替格式化,因此如果pressed然后您可以设置 mx 值,否则将其设置为 mrx 值 -
类似这样的:
mx = 0 mr = 0并在def中使用:if pressed: mx = x else: mrx = x