简体   繁体   English

如何在 Python 3.6.1 中检测鼠标点击

[英]How to detect mouse click in Python 3.6.1

I am making a program (just for fun) that plays a sound when you click with your mouse, problem is I don't know how to detect mouse clicks... There are many questions with answers about this topic already but for some reason it just doesn't work for me.我正在制作一个程序(只是为了好玩),当你用鼠标点击时它会播放声音,问题是我不知道如何检测鼠标点击......关于这个主题已经有很多问题和答案但出于某种原因它对我不起作用。 Either because they suggest pygame or Tkinter which uses a box so the user would need to click in the box to activate the sound, suggest outdated modules, suggest modules that are for some reason just impossible to get using internet and or pip install or the script just don't work.要么是因为他们建议使用盒子的 pygame 或 Tkinter,因此用户需要点击盒子来激活声音,建议过时的模块,建议由于某种原因无法使用互联网和/或 pip 安装或脚本的模块只是不工作。 So what is a currently up to date way (which doesn't require the user to click in a box like pygame etc.) to detect mouse clicks?那么目前最新的检测鼠标点击的方法是什么(不需要用户点击pygame等框)? (btw, I use windows 7) (顺便说一句,我使用的是 Windows 7)

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx.在程序外检测鼠标事件的唯一方法是使用 SetWindowsHookEx 安装 Windows 挂钩。 The pyHook module encapsulates the nitty-gritty details. pyHook 模块封装了细节。

import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

pyHook might be tricky to use in a pure Python script, because it requires an active message pump pyHook 在纯 Python 脚本中使用起来可能很棘手,因为它需要一个活动的消息泵

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM