8
$\begingroup$

How can I create a keyboard shortcut for a specific operator with using the python API?

$\endgroup$

1 Answer 1

12
$\begingroup$

Minimal add-on example using keymap_items.new() to register a new hotkey CtrlW in 3d View:

import bpy

bl_info = {
    "name": "Your Addon Name",
    "author": "Author Name",
    "version": (0, 1),
    "blender" : (2, 80, 0),
    "location": "",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": ""
}


class OBJECT_OT_CustomOp(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    def execute(self, context):
        print (self.bl_idname)
        return {'FINISHED'}


addon_keymaps = []

def register():
    bpy.utils.register_class(OBJECT_OT_CustomOp)
    
    # Add the hotkey
    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon
    if kc:
        km = wm.keyconfigs.addon.keymaps.new(name='3D View', space_type='VIEW_3D')
        kmi = km.keymap_items.new(OBJECT_OT_CustomOp.bl_idname, type='W', value='PRESS', ctrl=True)
        addon_keymaps.append((km, kmi))


def unregister():
    bpy.utils.unregister_class(OBJECT_OT_CustomOp)
    
    # Remove the hotkey
    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)
    addon_keymaps.clear()


if __name__ == "__main__":
    register()

    # test call
    #bpy.ops.object.simple_operator()
$\endgroup$
2
  • 1
    $\begingroup$ what happens if there's already an addon keymap named '3D View'? $\endgroup$ Commented Oct 27, 2021 at 19:53
  • $\begingroup$ @MartyFouts — [ What if there's already an addon keymap named 3D View? ] — In that case no exception raised, just new shortcut will be added (while keeping old ones). If shortcut for this operator already exits in this context – the shortcut will be rewritten. $\endgroup$
    – Yaroslav
    Commented Aug 15 at 14:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .