如何记录鼠标的移动,直到用Python按下某个键? [英] How to record the mouse movement until a key is pressed with Python?

查看:192
本文介绍了如何记录鼠标的移动,直到用Python按下某个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使功能mouse.record()一直运行到按下某个键而不是鼠标按钮为止. mouse.record()是python模块mouse中的函数: (mouse/__init__.py)

I want to make the function mouse.record() run until a key is pressed, rather than a mouse button. The mouse.record() is a function from the python module mouse: (mouse/__init__.py)

def record(button=RIGHT, target_types=(DOWN,)):
    """
    Records all mouse events until the user presses the given button. Then returns the list of events recorded. Pairs well with `play(events)`.

    Note: this is a blocking function. Note: for more details on the mouse hook and events see `hook`.
    """
    recorded = []
    hook(recorded.append)
    wait(button=button, target_types=target_types)
    unhook(recorded.append)
    return recorded

我认为我可以将mouse模块与keyboard模块合并,以实现记录鼠标移动直到发生键盘事件的功能.有一个类似的键盘功能可能很方便: (keyboard/__init__.py)

I've thought that I could merge the mouse module with the keyboard module to achieve a function that records the mouse movement until a keyboard event. There is a similar keyboard function that could be handy: (keyboard/__init__.py)

def record(until='escape', suppress=False, trigger_on_release=False):
    """
    Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`.

    Note: this is a blocking function. Note: for more details on the keyboard hook and events see `hook`.
    """
    start_recording()
    wait(until, suppress=suppress, trigger_on_release=trigger_on_release)
    return stop_recording()

因此,总而言之,我要实现的功能是使用Python模块mousekeyboard记录直到键盘事件为止的鼠标移动. 这可能吗?

So, to sum it up, what I want to achieve is a function that records the mouse movement until a keyboard event using the Python modules mouse and keyboard. Is this possible?

推荐答案

您可以合并两者而不会弄乱模块文件:

You can merge both without messing up with the module files:

1)使用mouse.hook()记录事件而无需等待(就像mouse.record()那样).它需要一个函数并返回该事件.
2)使用keyboard.wait(key)等待按键被按下
3)使用mouse.unhook()停止录制.

1) Use mouse.hook() to record events without waiting (like it happens with mouse.record() ). It takes a function and return it that event.
2) Use keyboard.wait(key) to wait for the key to be pressed
3) Use mouse.unhook() to stop recording.

这是示例代码:

import mouse
import keyboard


events = []                 #This is the list where all the events will be stored
mouse.hook(events.append)   #starting the recording
keyboard.wait("a")          #Waiting for 'a' to be pressed
mouse.unhook(events.append) #Stopping the recording

这篇关于如何记录鼠标的移动,直到用Python按下某个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆