1
$\begingroup$

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

$\endgroup$
6
$\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$
1
  • $\begingroup$ what happens if there's already an addon keymap named '3D View'? $\endgroup$ Oct 27 '21 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.