Bone parenting without offset using Python?

import bpy

ob = bpy.data.objects
child = ob['cube']
parent = ob['armature']
bone = parent.pose.bones['bone']

child.parent = parent
child.parent_type = 'BONE'
child.parent_bone = bone

I wrote the script above to carry out bone parenting with Python.
The parenting setting works correctly, but at the end, the child object’s transformation will have an offset.
How can I achieve bone parenting without offset?

You can eliminate the offset by copying the object’s matrix_world before parenting it, then restore it afterwards.

mat = child.matrix_world.copy()

child.parent = parent

child.matrix_world = mat
1 Like