5 Best Ways to Create a Hotkey in Python

πŸ’‘ Problem Formulation: Creating hotkeys in Python allows users to register key combinations that trigger specific functions while an application is running. For instance, pressing ‘Ctrl+Shift+A’ might need to automatically run a script to automate a particular task. This article provides various methods to implement this functionality within a Python environment, detailing the input (hotkey combination) and the desired output (triggered function).

Method 1: Using the keyboard Module

The keyboard module in Python makes it straightforward to read both individual keypresses and complex hotkeys. It allows you to listen for global hotkeys, register actions for when keys are pressed and works with both specific keys and complex key combinations.

Here’s an example:

import keyboard

def my_function():
    print("Hotkey activated!")

keyboard.add_hotkey('ctrl+shift+a', my_function)

keyboard.wait('esc')

Output: When the ‘Ctrl+Shift+A’ keys are pressed together, “Hotkey activated!” is printed to the console.

This code snippet shows how to use the keyboard library to define a hotkey that, when pressed, calls the my_function. The function is kept running and listening for the hotkey until ‘Escape’ key is pressed due to keyboard.wait('esc').

Method 2: Using the pyhk Library

The pyhk library is another straightforward tool for creating hotkeys in Python. It allows you to define a hotkey and associate it with a function in a simple and clean way.

Here’s an example:

import pyhk

def my_function():
    print("Hotkey activated!")

# Create a hotkey object
hot = pyhk.pyhk()

# Add a hotkey
hot.addHotkey(['Ctrl', 'Shift', 'A'], my_function)

# Start the event loop
hot.start()

Output: When the ‘Ctrl+Shift+A’ keys are pressed together, “Hotkey activated!” is printed to the console.

In this snippet, the pyhk library is used to attach the function my_function to the ‘Ctrl+Shift+A’ hotkey. Once the hotkey is defined, the hot.start() command begins the event loop to listen for the hotkey press.

Method 3: Employing the pynput Library

The pynput library monitors input devices. It offers control and monitoring of the keyboard, allowing you to listen to hotkeys and perform actions based on key states.

Here’s an example:

from pynput import keyboard

def on_activate():
    print("Hotkey activated!")

hotkey = keyboard.HotKey(
    keyboard.HotKey.parse('++a'),
    on_activate
)

listener = keyboard.Listener(
    on_press=hotkey.press,
    on_release=hotkey.release
)
listener.start()

listener.join()

Output: When the ‘Ctrl+Shift+A’ keys are pressed together, “Hotkey activated!” gets printed to the console.

This code uses the pynput.keyboard to create a hotkey; when ‘Ctrl+Shift+A’ is pressed, it triggers the on_activate function. The listener object listens for key presses and releases, which it then forwards to the hotkey object.

Method 4: Using the ctypes Library on Windows

The ctypes library allows Python code to call C functions directly. On Windows, you can use this to register system-wide hotkeys using the Windows API.

Here’s an example:

import ctypes
import time

user32 = ctypes.windll.user32

HOTKEYS = {
    1: (user32.VK_F1, user32.MOD_ALT)
}

def handle_win_f1():
    print("Hotkey activated!")

HOTKEY_ACTIONS = {
    1: handle_win_f1
}

for id, (vk, modifiers) in HOTKEYS.items():
    if not user32.RegisterHotKey(None, id, modifiers, vk):
        print("Unable to register hotkey")

try:
    msg = ctypes.wintypes.MSG()
    while user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == user32.WM_HOTKEY:
            action_to_take = HOTKEY_ACTIONS.get(msg.wParam)
            if action_to_take:
                action_to_take()
        user32.TranslateMessage(ctypes.byref(msg))
        user32.DispatchMessageA(ctypes.byref(msg))
finally:
    for id in HOTKEYS.keys():
        user32.UnregisterHotKey(None, id)

Output: When the ‘Alt+F1’ keys are pressed together, “Hotkey activated!” is printed to the console.

This script uses the Windows API through ctypes to register ‘Alt+F1’ as a global hotkey that will call handle_win_f1 when pressed. The message loop waits for the hotkey event, and upon receiving it, executes the registered function.

Bonus One-Liner Method 5: Using a tkinter Shortcut

The tkinter library, which is bundled with Python for building graphical user interfaces (GUIs), supports keybindings as well.

Here’s an example:

import tkinter as tk

def my_function(event):
    print("Hotkey activated!")

root = tk.Tk()
root.bind('', my_function)
root.mainloop()

Output: When the ‘Ctrl+Shift+A’ keys are pressed while the GUI window has focus, “Hotkey activated!” is printed to the console.

This one-liner sets up a GUI window using tkinter and binds ‘Ctrl+Shift+A’ to my_function. As long as the GUI window is the active window, pressing the hotkey will execute the function.

Summary/Discussion

  • Method 1: keyboard Module. Easy to use. Cross-platform. Requires root/administrator permissions.
  • Method 2: pyhk Library. Simple and clean. Not well-known or widely used. Limited support and may require specific versions of Python.
  • Method 3: pynput Library. Flexible. Can handle a variety of inputs not just hotkeys. Can be more complex to use than other methods.
  • Method 4: ctypes Library on Windows. Powerful low-level access. Windows-specific. More complex and verbose.
  • Bonus Method 5: tkinter Shortcut. Built into Python. Only works within GUI context. Convenient for Python GUI applications.