如何通过在Python中单击鼠标左键来触发函数?

时间:2017-06-28 23:59:39

标签: python pygame pyhook

我想首先说我是Python的新手,所以如果这个问题听起来很愚蠢,我很抱歉。

每当我按下鼠标左键时,我只是在寻找一种简单的触发功能的方法。 谁能说明我如何实现这一目标?非常感谢例子。

我的代码现在:

import win32api
import win32con
import time
from random import randint
import pythoncom, pyHook 

def OnMouseEvent(event): #triggers mouseClick function
    mouseClick(event)
    return True

def mouseClick(event):

    if event.MessageName == "mouse left up": # makes sure that's the event I'm looking for
        a = True # disables hm.MouseAll
        return a
        time.sleep(0.01)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        time.sleep(0.005)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        time.sleep(0.01)
        a = False # enables hm.MouseAll back
        return a


a = False      
# create a hook manager
hm = pyHook.HookManager()
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()
# watch for all mouse events
while True:
    if a == False:
        hm.MouseAll = OnMouseEvent # Triggers OnMouseEvent function       
    else:
        pass

1 个答案:

答案 0 :(得分:1)

我的理解是你已经准备好了功能。我会使用Pygame包。

for event in pygame.event.get():    
    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
        nameoffunction()

更改event.button == 1:中的数字1将改变单击鼠标按钮的位置。

编辑1

run = 1 
while run == 1:
    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
        print("Message")

PyGame需要一个窗口,所以如果你只想测试一下,我会用...

编辑2

if win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0):
    print("Message")

x,y = x和y框角的起始坐标 0,0 =盒子的其他角落(我认为) 知道鼠标是否在“框”内,你点击它应该工作 (我没有安装win32api所以没有运行任何测试)

相关问题