I'm having problems with holding down the arrow keys specifically with python

42 Views Asked by At

I can't seem to get this to work, i've tried using both the pyautogui and the keyboard modules. What I'm trying to achieve is to be able to hold down the right arrow for 1 second every time the counter reaches 3. I checked if the codeblock actually runs with print, and it does. Please help me.

Please note that I'm new to most python related stuff.

Here's my code:

import time
import pyautogui
import keyboard

def hold_key(key, duration):
    keyboard.press(key)
    time.sleep(duration)
    keyboard.release(key)


def main():
    interval = 3  # seconds
    repeat_count = 3
    right_arrow_duration = 1
    default_key_duration = 1
    counter = 0

    while True:
        counter = counter + 1

        # Hold "D" key for 2 seconds
        hold_key('d', default_key_duration)
        # Sleep for the specified interval
        time.sleep(interval)

        # Hold right arrow key for 0.5 seconds every 3 times
        if (counter == repeat_count):
            counter = 0
            with pyautogui.hold('right'): # Here's the problem
                time.sleep(1)
            print("Right!" + str(counter))

if __name__ == "__main__":
    main()

I tried to run the code with pyautogui.KeyDown(), pyautogui.KeyUp(), keyboard.press(), keyboard.release(). None of these seem to be able to hold down the arrow keys as expected, though they work with any other keys.

0

There are 0 best solutions below