检测按下的两个鼠标按钮
Detecting both mouse buttons held down
我是 python 的新手,我发现了一个代码可以在按下和释放时检测鼠标按钮,但我希望“x”在两个按钮都按下时变为 True,我该怎么做这个
# This function will be called when any key of mouse is pressed
def on_click(*args):
# see what argument is passed.
print(args)
if args[-1]:
# Do something when the mouse key is pressed.
print('The "{}" mouse key has held down'.format(args[-2].name))
elif not args[-1]:
# Do something when the mouse key is released.
print('The "{}" mouse key is released'.format(args[-2].name))
# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
# Listen to the mouse key presses
listener.join()
要检测两个按钮是否同时按下,需要三个变量(在程序开始时在 on_click 函数之外初始化):
global leftPressed, rightPressed, bothPressed
leftPressed = False
rightPressed = False
bothPressed = False
*注意变量在这里是全局的,因为 on_click 的多个版本将访问和修改变量
然后,在第一个 if 语句中(按下鼠标按钮时):
if args[-2].name == "left":
leftPressed = True
elif args[-2].name == "right":
rightPressed = True
if leftPressed and rightPressed:
# if both left and right are pressed
bothPressed = True
并且在第二个 if 语句中(当鼠标按钮被释放时)
if args[-2].name == "left":
leftPressed = False
elif args[-2].name == "right":
rightPressed = False
# as one key has been released, both are no longer pressed
bothPressed = False
print(bothPressed)
最后,要从函数 on_click 中访问全局变量,请将此行放在函数的开头:
global leftPressed, rightPressed, bothPressed
在此处查看代码的完整版本:
我是 python 的新手,我发现了一个代码可以在按下和释放时检测鼠标按钮,但我希望“x”在两个按钮都按下时变为 True,我该怎么做这个
# This function will be called when any key of mouse is pressed
def on_click(*args):
# see what argument is passed.
print(args)
if args[-1]:
# Do something when the mouse key is pressed.
print('The "{}" mouse key has held down'.format(args[-2].name))
elif not args[-1]:
# Do something when the mouse key is released.
print('The "{}" mouse key is released'.format(args[-2].name))
# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
# Listen to the mouse key presses
listener.join()
要检测两个按钮是否同时按下,需要三个变量(在程序开始时在 on_click 函数之外初始化):
global leftPressed, rightPressed, bothPressed
leftPressed = False
rightPressed = False
bothPressed = False
*注意变量在这里是全局的,因为 on_click 的多个版本将访问和修改变量
然后,在第一个 if 语句中(按下鼠标按钮时):
if args[-2].name == "left":
leftPressed = True
elif args[-2].name == "right":
rightPressed = True
if leftPressed and rightPressed:
# if both left and right are pressed
bothPressed = True
并且在第二个 if 语句中(当鼠标按钮被释放时)
if args[-2].name == "left":
leftPressed = False
elif args[-2].name == "right":
rightPressed = False
# as one key has been released, both are no longer pressed
bothPressed = False
print(bothPressed)
最后,要从函数 on_click 中访问全局变量,请将此行放在函数的开头:
global leftPressed, rightPressed, bothPressed
在此处查看代码的完整版本: