我正在使用PyAutoGUI库。如何知道是否按下了鼠标左键?
这就是我想要做的事情:
if(leftmousebuttonpressed):
print("left")
else:
print("nothing")
答案 0 :(得分:4)
(我是PyAutoGUI的作者。)我可以确认目前PyAutoGUI无法读取/记录点击或击键。这些功能在路线图上,但目前还没有专门针对它们的任何资源或时间表。
答案 1 :(得分:2)
我不认为你可以使用PyAutoGui来监听鼠标点击。
而是尝试Pyhook(来自他们的源页面):
import pythoncom, pyHook
def OnMouseEvent(event):
# called when mouse events are received
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Position:',event.Position
print 'Wheel:',event.Wheel
print 'Injected:',event.Injected
print '---'
# return True to pass the event to other handlers
return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.MouseAll = OnMouseEvent
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()
我相信你能做到这一点:
import pyHook, pythoncom
def left_down():
print("left down")
def right_down():
print("right down")
hm = pyHook.HookManager()
hm.SubscribeMouseLeftDown(left_down)
hm.SubscribeMouseRightDown(right_down)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
他们也会做键盘活动,只需看看他们的api。
编辑: 这是他们的迷你教程:https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/
此外PyHook仅适用于Windows(感谢John Doe指出)
答案 2 :(得分:1)
像上面的评论中提到的 Sir Al Sweigart 一样,我寻找了效果很好的 pynput 模块。请参阅文档和 PyPi 说明:
使用pip安装库:
pip install pynput
源于原始文档的简单代码版本:
from pynput import mouse
def on_click(x, y, button, pressed):
if button == mouse.Button.left:
print('{} at {}'.format('Pressed Left Click' if pressed else 'Released Left Click', (x, y)))
return False # Returning False if you need to stop the program when Left clicked.
else:
print('{} at {}'.format('Pressed Right Click' if pressed else 'Released Right Click', (x, y)))
listener = mouse.Listener(on_click=on_click)
listener.start()
listener.join()
请参阅原始文档中监视鼠标标题下的代码。 https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse