pythonkeyboardhotkeys

How am I meant to use the keyboard python module to create hotkeys using custom functions with parameters?


I've been trying to make a thing that presses a button a certain amount of times when a hotkey is pressed. It's not been working well.

Here is the code:

import keyboard
def moveArrow(times: int):
    while times > 0:
        keyboard.press_and_release("a")
        times = times - 1
keyboard.add_hotkey("ctrl+shift+g", moveArrow, 20, True)
keyboard.wait("esc")

It keeps spitting out this error when I attempt to use the hotkey:

Error in keyboard hook:
Traceback (most recent call last):
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\_winkeyboard.py", line 541, in low_level_keyboard_handler
    should_continue = process_key(event_type, vk, scan_code, is_extended)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\_winkeyboard.py", line 529, in process_key
    return callback(KeyboardEvent(event_type=event_type, scan_code=scan_code or -vk, name=name, is_keypad=is_keypad))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\__init__.py", line 
268, in direct_callback
    callback_results = [callback(event) for callback in self.blocking_hotkeys[hotkey]]
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\__init__.py", line 
268, in <listcomp>
    callback_results = [callback(event) for callback in self.blocking_hotkeys[hotkey]]
                        ^^^^^^^^^^^^^^^
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\__init__.py", line 
649, in <lambda>
    handler = lambda e: (event_type == KEY_DOWN and e.event_type == KEY_UP and e.scan_code in _logically_pressed_keys) or (event_type == e.event_type and callback())

                                             ^^^^^^^^^^
  File "c:\Users\ricky\AppData\Local\Programs\Python\Python311\Lib\site-packages\keyboard\__init__.py", line 
637, in <lambda>
    callback = lambda callback=callback: callback(*args)
                                         ^^^^^^^^^^^^^^^
TypeError: __main__.moveArrow() argument after * must be an iterable, not int

The code should type "a" twenty times upon pressing ctrl+shift+g at the same time, whilst also stopping any other program from being affected from the button presses. Instead it does neither of those and gives me an error. I've also tried using args = (20) but then the true next to it gives me an error.


Solution

  • As juanpa.arrivilliga commented, I needed to use an interable, like (20,) instead of an int.