Search code examples
pythonpyautogui

How do I type a numpad plus-sign (+) with `pyautogui`?


For some GUI automation, I need to send a keystroke for the numpad plus-sign. (For some silly reason, the ancient software I'm interfacing with distinguishes between the numpad plus-sign and the top-row plus-sign...)

I can use pyautogui.press('num1') to send a 1 keystroke from the numpad, but 'num+' and 'numplus', etc, don't seem to exist.


Solution

  • After some digging, I found that the pyautogui.platformModule contains the mappings for this. It varies based on your OS; Windows and Linux solutions are shown in the code block below -- something similar should be possible for Mac.

    Similar keyboard mappings can be made for other keys. I couldn't find a good source for the Linux key mappings, but the windows ones can be found here.

    import pyautogui as gui
    
    gui.platformModule.keyboardMapping.update({'numplus':gui.platformModule._display.keysym+_to_keycode(gui.platformModule.Xlib.XK.string_to_keysym('KP_Add'))}) # Linux: KP_Add found by random googling
    gui.platformModule.keyboardMapping.update({'numplus':0x6B}) # Windows: VK_ADD from https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
    gui.press('numplus')
    

    Note that pyautogui.platformModule comes from the file _pyautogui_x11 or _pyautogui_win, etc, and is just aliased to platformModule.