I would like to set active shape key using Python. I know that I can use following code for this purpose:

bpy.context.active_object.active_shape_key_index = some_index

but, when I have several shape keys, then I don't know how to get this index from given shape key:

sh_key = bpy.context.active_object.data.shape_keys.key_blocks["shape_key_name"]

There is no attribute called index in object sh_key. I tried to use bpy.context.active_object.active_shape_key, but this attribute is read only. Thanks for your help.


Hi here is some quick code from the python console,

I have an active object with a number of shapekeys, "Key 1" being one, I find the index using find(...) then set the active_shape_key_index to this number.

find(...) will return -1 if a key of that name is not found.

>>> index = C.object.data.shape_keys.key_blocks.find('Key 1')
>>> index

>>> C.object.active_shape_key_index = index
| improve this answer | |
  • $\begingroup$ At about the same time too. Suggest using key_blocks.get("shape_key_name") and testing against None, can save hassles down the line for all collections in blender. $\endgroup$ – batFINGER Sep 21 '16 at 13:43

I thing, I found solution, but it is a little bit complicated (API of vertex groups is more straightforward). You can set active shape key, when you know its name, using following code:

obj = bpy.context.active_object
shape_key = obj.data.shape_keys.key_blocks["shape_key_name"]
keys = obj.data.shape_keys.key_blocks.keys()
shape_key_index = keys.index(shape_key.name)
obj.active_shape_key_index = shape_key_index
| improve this answer | |

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.