How to make python play a mouse events recording only WHILE left key is pressed?

472 Views Asked by At

I'm new to python and I'm trying to learn how to use the mouse and keyboard modules. I am trying to write some code that plays a recording while I'm holding left click, I think the issue is that this may be only part of the recording depending on how long I hold it. This is what I have so far but it isn't playing the 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


def onleftclick():
    while mouse.is_pressed(button='left') == True:
        mouse.play(events)


mouse.on_click(onleftclick)
keyboard.wait('esc')
2

There are 2 best solutions below

3
On

Use a keystroke to play back the recording. The recording won't play if you're using the mouse.

Try this code. Press a to play back the 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
print('playback...')
mouse.unhook(events.append) #Stopping the recording
mouse.play(events)

keyboard.wait('esc')
print('bye')
0
On

you could do:

import keyboard
while True:
    #lets just say that you want to detect q and left key pressed
    if keyboard.is_pressed('left') and keyboard.is_pressed('q'):
        print('left key and q pressed')