1
$\begingroup$

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.

$\endgroup$

2 Answers 2

2
$\begingroup$

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
1

>>> C.object.active_shape_key_index = index
>>> 
$\endgroup$
1
  • 1
    $\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
    Commented Sep 21, 2016 at 13:43
1
$\begingroup$

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
$\endgroup$

You must log in to answer this question.

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