python - 检测按住的两个鼠标按钮
问题描述
我是python的新手,我发现了一个代码,可以在按住并释放鼠标按钮时检测鼠标按钮,但是我希望“x”在两个按钮都被按住时变为真,我该怎么做
# 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
在此处查看完整版本的代码:
推荐阅读
- amazon-web-services - AWS 错误消息:使用 AWS KMS 托管密钥指定服务器端加密的请求需要 AWS 签名版本 4
- python - 如何在渲染页面之前进行过滤?
- c++ - C++ 2D 数组和函数
- flowtype - 我可以在 Flow 中使用 JSDoc 注释来强制按文件输入吗?
- unison-lang - 将文本列表统一映射到其字母数
- ansible - Ansible wait_for_connection 直到主机准备好使用ansible?
- python - 我无法从本地机器上生成的 url 访问我的烧瓶应用程序
- solr - 如何在 Solr 中使用 Config API 添加具有多个字典的建议器组件?
- java - SpringBoot Bean Validation 注解
- r - 使用for循环从r中的数据框中删除特定列