Sub topic 19
Building and posing a rig with Python
This chapter assumes you can run scripts in Blender's Scripting workspace, know the Object, Edit and Pose modes, and understand the difference between rest pose and pose. It also assumes you know how the Armature modifier and vertex groups bind a mesh to bones. Here you will script that whole workflow. The examples target Blender 4.x.
Where each piece lives in the API
Most scripting mistakes in rigs come from not knowing which data block owns what. An armature is split in two, and each half has its own bone type.
| What you want | Where it lives | Available in |
|---|---|---|
| Rest-pose head, tail, roll, parent | `armature.edit_bones` | Edit Mode only |
| Read-only rest data (`head_local`, `tail_local`) | `armature.bones` | Any mode |
| Rotation, location, scale, constraints, keyframes | `armature_object.pose.bones` | Any mode, once the bones exist |
| Which bone deforms which vertices | Vertex groups on the mesh object | Any mode |
Edit bones exist only while the armature is in Edit Mode. When you leave Edit Mode, Blender frees them. Keeping a Python reference to one and using it later can crash Blender or raise an error. Store bone names instead, and look the bone up again when you need it.
Step 1: Build the bones
This script builds a two-bone chain and a box to deform. It runs in a default scene. Run it once, because a second run creates duplicates.
import bpy
def build_armature(name):
arm_data = bpy.data.armatures.new(name)
arm_obj = bpy.data.objects.new(name, arm_data)
bpy.context.collection.objects.link(arm_obj)
bpy.context.view_layer.objects.active = arm_obj
arm_obj.select_set(True)
bpy.ops.object.mode_set(mode='EDIT')
try:
upper = arm_data.edit_bones.new("upper")
upper.head = (0, 0, 0)
upper.tail = (0, 0, 1)
lower = arm_data.edit_bones.new("lower")
lower.head = (0, 0, 1)
lower.tail = (0, 0, 2)
lower.parent = upper
lower.use_connect = True
finally:
bpy.ops.object.mode_set(mode='OBJECT')
return arm_obj
rig = build_armature("ScriptRig")
bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1))
box = bpy.context.active_object
box.name = "RigBox"The try/finally block guarantees that you leave Edit Mode even if a line fails. Otherwise the scene stays in Edit Mode and later operators fail.
Two details matter here:
- A bone whose head and tail are identical has zero length. Blender deletes it when you leave Edit Mode.
use_connect = Truesnaps the child's head to the parent's tail. Set the head position first. Then the connection does not move anything you did not intend to move.
Step 2: Bind the mesh
Binding by script means doing by hand what Automatic Weights does. You create one vertex group per deforming bone and name it exactly as the bone. You then add an Armature modifier that points at the rig.
import bpy
rig = bpy.data.objects["ScriptRig"]
box = bpy.data.objects["RigBox"]
upper_group = box.vertex_groups.new(name="upper")
lower_group = box.vertex_groups.new(name="lower")
# Local z is -1 for the bottom face and +1 for the top face of this cube
bottom = [v.index for v in box.data.vertices if v.co.z < 0]
top = [v.index for v in box.data.vertices if v.co.z >= 0]
upper_group.add(bottom, 1.0, 'REPLACE')
lower_group.add(top, 1.0, 'REPLACE')
mod = box.modifiers.new(name="Armature", type='ARMATURE')
mod.object = rig
box.parent = rigThe modifier matches groups to bones by name. If you rename a bone later, the group no longer matches and that bone stops deforming the mesh. No error appears.
vertex_group.add(indices, weight, type) takes a list of vertex indices. The type is 'REPLACE', 'ADD' or 'SUBTRACT'. A cube has only eight vertices, so the bend will look crude. A subdivided mesh with gradient weights bends smoothly.
Step 3: Pose and keyframe
Pose bones belong to the object, not the armature data. Blender defaults every pose bone to quaternion rotation, so writing to rotation_euler does nothing until you change rotation_mode.
import bpy
import math
rig = bpy.data.objects["ScriptRig"]
pbone = rig.pose.bones["lower"]
pbone.rotation_mode = 'XYZ'
pbone.rotation_euler = (0, 0, 0)
pbone.keyframe_insert(data_path="rotation_euler", frame=1)
pbone.rotation_euler = (math.radians(60), 0, 0)
pbone.keyframe_insert(data_path="rotation_euler", frame=24)Bone rotations are relative to the bone's own rest orientation and its parent. The rest pose in armature.bones never changes, so you can reset a pose by zeroing the pose bone transforms.
Step 4: Add an IK constraint
IK and the keyframes above fight each other. A keyframed rotation on lower is overridden by an IK chain that includes it. Use one or the other on a given bone, or run the IK script on a copy of the rig.
import bpy
rig = bpy.data.objects["ScriptRig"]
target = bpy.data.objects.new("IK_Target", None)
target.empty_display_type = 'SPHERE'
target.location = (0, 1, 1.5)
bpy.context.collection.objects.link(target)
ik = rig.pose.bones["lower"].constraints.new('IK')
ik.target = target
ik.chain_count = 2chain_count counts the constrained bone itself plus its parents. A value of 2 here affects lower and upper. A value of 0 means the whole chain up to the root.
Common errors
RuntimeError: Operator bpy.ops.object.mode_set.poll() failed: no active object, or the active object is hidden or not in the view layer. Setview_layer.objects.activefirst.- Posing has no visible effect: either
rotation_modedoes not match the property you wrote, or the Armature modifier is missing or has no object set. - Mesh does not follow the bone: the vertex group name differs from the bone name, or the group has no vertices with weight above zero.
- Bone vanished: head equals tail.
- Name collisions:
bpy.data.objects.new("ScriptRig", ...)on a second run createsScriptRig.001, and later lookups by name find the old one. Remove old data or use a new name per run.
Exercise
You set pbone.rotation_euler = (math.radians(90), 0, 0) on a new pose bone, and the bone does not move. The Armature modifier and vertex groups are correct. What is the likely cause, and what is the fix?
Show answer
The pose bone is still using its default rotation mode, which is quaternion, so Blender ignores rotation_euler. Set pbone.rotation_mode = 'XYZ' before assigning the Euler values. Alternatively, write to rotation_quaternion.
Exercise
After the script leaves Edit Mode, you run upper.tail = (0, 0, 3) using the upper variable from the build function, and Blender errors or behaves unpredictably. Why, and how do you change the tail correctly?
Show answer
Edit bones are freed when you leave Edit Mode, so the variable no longer points at valid data. Re-enter Edit Mode with bpy.ops.object.mode_set(mode='EDIT'), fetch the bone with rig.data.edit_bones["upper"], set the tail, and return to Object Mode.