如何解决检测按住的两个鼠标按钮
我是 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,bothPressed
在此处查看代码的完整版本:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。