[PYTHON] [Blender] Assign shortcut keys to your own functions inside the script

Some Blender features and add-ons are assigned shortcut keys to help you perform frequently used functions quickly. As with Blender features, you can assign shortcut keys to features in your own add-ons. For example, the add-on "Screencast Key" that displays the keys pressed with the keyboard or mouse on the screen is one example.

In this article, I will show you how to assign a shortcut key to your own function based on a sample that enlarges / reduces the selected object when you press the assigned short key.

sample

shortcut_key.py



import bpy


bl_info = {
    "name": "Tutorial: Shortcut key",
    "author": "Nutti",
    "version": (1, 0),
    "blender": (2, 74, 0),
    "location": "Object > Tutorial: Shortcut key",
    "description": "Tutorial: Shortcut key.",
    "warning": "",
    "support": "COMMUNITY",
    "wiki_url": "",
    "tracker_url": "",
    "category": "Object"
}

addon_keymaps = []    #List of registered shortcut keys


class ObjectScaleUp(bpy.types.Operator):
    """Enlarge the selected object"""
    
    bl_idname = "object_transform.object_scale_up"
    bl_label = "Scale Up Object"
    bl_description = "Scale up selected object"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        active_obj = context.active_object
        active_obj.scale = active_obj.scale * 2.0    #Double the selected object
        return {'FINISHED'}


class ObjectScaleDown(bpy.types.Operator):
    """Shrink selected object"""
    
    bl_idname = "object_transform.object_scale_down"
    bl_label = "Scale Down Object"
    bl_description = "Scale down selected object"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        active_obj = context.active_object
        active_obj.scale = active_obj.scale / 2.0    #1 selected object/Reduced to 2
        return {'FINISHED'}


def register():
    bpy.utils.register_module(__name__)
    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon
    #Create a list of shortcut keys to register
    # (Bpy to run when a key is pressed.types.Operator bl_idname,Key,Event,Ctrl key,Alt key,Shift key)
    key_assign_list = [
        (ObjectScaleUp.bl_idname, "U", "PRESS", True, True, False),
        (ObjectScaleDown.bl_idname, "D", "PRESS", True, True, False),
        ]
    if kc:
        km = kc.keymaps.new(name="3D View", space_type="VIEW_3D")    #Registered as a shortcut key for "View 3D"
        for (idname, key, event, ctrl, alt, shift) in key_assign_list:
            kmi = km.keymap_items.new(
                idname, key, event, ctrl=ctrl, alt=alt, shift=shift)    #Shortcut key registration
            addon_keymaps.append((km, kmi))


def unregister():
    bpy.utils.unregister_module(__name__)
    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)    #Unregister shortcut key
    addon_keymaps.clear()


if __name__ == "__main__":
    register()

How to use

  1. Install the script by referring to Blender Wiki page.
  2. Select the object you want to scale.
  3. Press ** Ctrl + Alt + U ** at the same time to verify that the selected object has been magnified.
  4. Press ** Ctrl + Alt + D ** at the same time to verify that the selected object has been scaled down.

Sample explanation

The basic explanation of the Blender script is introduced in the following article, so here we will focus on the explanation of the newly added elements. [Blender] How to make a Blender plugin

Shortcut key registration

Register the shortcut key when installing the script. Before registering the shortcut key, get the keymap of the area to which the shortcut key is assigned with the bpy.context.window_manager.eyconfigs.addon.keymaps.new function and assign it to kmTo do. Since we are assigning a keymap to the "View3D" area this time, we have set the argument space_typeto View_3D```.

km.keymap_items.The argument passed to new is key_assign_I have registered in advance for list.



#### **`for (idname, key, event, ctrl, alt, shift) in key_assign_list:By key_assign_After expanding the list, km.keymap_items.Use the new function to register the shortcut key.`**

The meaning of each variable in the, for statement is shown below.

variable meaning
bl_idname Event to be executed when the shortcut key is pressed (bpy.types.Operatorofbl_idname
key Keyboard keys to register
event Opportunity to execute the event
(ex. "PRESS":The moment the key is pressed)
ctrl If you need to press the Ctrl key at the same time to raise an eventTrue
alt If you need to press the Alt key at the same time to raise an eventTrue
shift If you need to press the Shift key at the same time to raise an eventTrue

It seems that you can specify other arguments, but basically it will not be a problem if you just remember the above. If you want to know the specific arguments, please check from the following URL. http://www.blender.org/api/blender_python_api_2_63_14/bpy.types.KeyMapItems.html Finally, save the registration information in the global variable addon_keymaps in case you unregister the shortcut key.

By the way, in Blender, shortcut keys are already assigned to many functions, so it is surprisingly difficult to find a key with nothing assigned from a single key. In such cases, look at ** combinations with Ctrl, Shift, and Alt **. Combination keys are less likely to be already assigned than a single key, so it should be fairly easy to find a free key.

    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon
    #Create a list of shortcut keys to register
    # (Bpy to run when a key is pressed.types.Operator bl_idname,Key,Event,Ctrl key,Alt key,Shift key)
    key_assign_list = [
        (ObjectScaleUp.bl_idname, "U", "PRESS", True, True, False),
        (ObjectScaleDown.bl_idname, "D", "PRESS", True, True, False),
        ]
    if kc:
        km = kc.keymaps.new(name="3D View", space_type="VIEW_3D")    #Registered as a shortcut key for "View 3D"
        for (idname, key, event, ctrl, alt, shift) in key_assign_list:
            kmi = km.keymap_items.new(
                idname, key, event, ctrl=ctrl, alt=alt, shift=shift)    #Shortcut key registration
            addon_keymaps.append((km, kmi))

Unregister shortcut key

You need to unregister the shortcut key when uninstalling the script. To unregister the shortcut key, call `keymap_items.remove ()` with the information saved in addon_keymaps.

    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)    #Unregister shortcut key
    addon_keymaps.clear()

Recommended Posts

[Blender] Assign shortcut keys to your own functions inside the script
Assign tweets to shortcut keys
[Blender] Use OpenGL from inside the script
(Note) How to pass the path of your own module
[Blender] Script to check if the selected one is a mesh
Make the theme of Pythonista 3 like Monokai (how to make your own theme)
How to create your own Transform
Bridge ROS to your own protocol