How to bone parent an object using Python?

@kitsu:

It’s not a problem to switch modes as much as necessary in the script, I just need some method or some quirky hack that enables me to parent an object to each bone in an armature on a single script run. I’ve been playing about with the different modes, but still can’t parent an object to a bone that hasn’t first been selected with the mouse. Have you managed to find a way to do it? I would be very interested to know. :slight_smile:

I thought that either pose mode or object mode was necessary for the bone parenting to work. I get a “no active bone” error when running bpy.ops.object.parent_set(type=‘BONE’) in edit mode.

My latest script. It’s easy to check out the different modes:


import bpy

print('
#######################
')
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.select_name(name='Cube', extend=False)
bpy.ops.object.select_name(name='Armature', extend=True)

'''
bpy.ops.object.mode_set(mode='POSE')
pose_bones = bpy.context.object.pose.bones
for bone in pose_bones:
    if not bone.name == 'Bone.005':
        bone.select = False
bpy.context.object.pose.bones['Bone.005'].select = True
bpy.context.scene.update()

bpy.ops.object.parent_set(type='BONE')
'''

'''
bpy.ops.object.mode_set(mode='EDIT')
edit_bones = bpy.context.object.data.edit_bones
for bone in edit_bones:
    if not bone.name == 'Bone.005':
        bone.select = False
bpy.context.object.data.edit_bones['Bone.005'].select = True
bpy.context.scene.update()

bpy.ops.object.parent_set(type='BONE')
'''

bpy.ops.object.mode_set(mode='OBJECT')
bones = bpy.context.object.data.bones
for bone in bones:
    if not bone.name == 'Bone.005':
        bone.select = False
bpy.context.object.data.bones['Bone.005'].select = True
bpy.context.scene.update()

bpy.ops.object.parent_set(type='BONE')