Sub topic 17
Keyframing with Python
This chapter shows how to do from a script what you have done by hand in the 3D Viewport, the Timeline, and the Dope Sheet: set the frame range, insert keyframes, change interpolation, and inspect the result. It assumes you can open Blender's Text Editor and run a script with the Run Script button (Alt+P). It also assumes you know what a keyframe, an F-curve, and an action are from the earlier chapters.
What the scripting API mirrors
Every action in the interface has a counterpart in the bpy module. The mapping below is the working model for this chapter.
| In the interface | In Python |
|---|---|
| Frame range fields in the Timeline | `scene.frame_start`, `scene.frame_end` |
| Frame rate in Output properties | `scene.render.fps` and `scene.render.fps_base` |
| Clicking a frame in the Timeline | `scene.frame_set(n)` |
| Pressing I over a property | `obj.keyframe_insert(...)` |
| Alt+I over a property | `obj.keyframe_delete(...)` |
| Interpolation Mode menu (T) | `keyframe.interpolation` |
| Action and its F-curves | `obj.animation_data.action` and `action.fcurves` |
Inserting keyframes
The method keyframe_insert belongs to any object that holds animatable properties. It takes a data_path, which is the property name as a string, and an optional frame.
import bpy
scene = bpy.context.scene
scene.frame_start = 1
scene.frame_end = 48
obj = bpy.context.active_object
obj.location = (0.0, 0.0, 0.0)
obj.keyframe_insert(data_path="location", frame=1)
obj.location = (0.0, 0.0, 2.0)
obj.keyframe_insert(data_path="location", frame=24)This script needs an active object, such as the default cube. It sets the frame range to 1 through 48 and creates two keyframes. The object rises two units between frames 1 and 24. After frame 24 it holds its position, because Blender keeps the last keyframe's value past the final key.
The value comes from the property, not the frame
keyframe_insert records whatever value the property holds at the moment you call it. The frame argument only says where on the timeline to store that value. It does not move the playhead and it does not evaluate the animation at that frame. That is why the script assigns obj.location before each insert.
Useful arguments
index: The default is-1, which keys every component of a vector. Passindex=2to key only Z location.frame: If you leave it out, Blender uses the current frame.group: This names the channel group the F-curve is placed in, for examplegroup="Lift".
keyframe_insert returns True when a keyframe was inserted. It returns False or raises an error when the property cannot be animated. A misspelled data_path raises a TypeError, so check the property name against the tooltip in the interface (hold Ctrl+C over the field to copy its path).
import bpy
obj = bpy.context.active_object
ok = obj.keyframe_insert(data_path="location", index=2, frame=12, group="Lift")
print("Inserted:", ok)
removed = obj.keyframe_delete(data_path="location", index=2, frame=12)
print("Removed:", removed)The first call keys only the Z component at frame 12. The second removes that key again. keyframe_delete also returns a Boolean, and it returns False if no key exists at that frame.
Moving the playhead
Setting a property such as scene.frame_current = 12 changes the frame number, but Blender may not re-evaluate animated properties until the next update. Use frame_set, which changes the frame and evaluates the animation.
import bpy
scene = bpy.context.scene
scene.frame_set(12)
print("Current frame:", scene.frame_current)After this call, obj.location holds the interpolated value for frame 12. This is the same as clicking frame 12 in the Timeline. It is also how you sample an animation from a script: call frame_set in a loop and read the properties.
Setting interpolation
New keyframes use the default interpolation from your Preferences, which is normally Bezier. To change it, you edit the keyframe points inside the action's F-curves.
import bpy
obj = bpy.context.active_object
action = obj.animation_data.action
for fcurve in action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'This is the scripted equivalent of selecting all keys in the Dope Sheet and choosing Linear from the Interpolation Mode menu (T).
The loop uses the F-curve access found in Blender 2.8 through 4.x. Newer versions with layered actions may access F-curves differently, through slots and channel bags, so check the Python API reference for your version if action.fcurves is missing.
Other values for interpolation include 'CONSTANT' and 'BEZIER'. You can also set keyframe.type to 'BREAKDOWN', 'EXTREME', 'JITTER', or 'MOVING_HOLD' to match the keyframe types in the Dope Sheet.
Inspecting what you created
Each F-curve is one animated channel. Location produces three F-curves, one for each of X, Y, and Z, so a script that keys location once creates three curves. The data_path names the property and array_index selects the component. Each keyframe point has co, a pair of frame and value.
import bpy
obj = bpy.context.active_object
action = obj.animation_data.action
print("Action:", action.name)
for fcurve in action.fcurves:
print(fcurve.data_path, fcurve.array_index)
for kp in fcurve.keyframe_points:
frame, value = kp.co
print(" frame", frame, "value", round(value, 3), kp.interpolation)Reading this output is a quick way to confirm that a script made the keys you intended, without opening the Dope Sheet.
Common errors
AttributeError: 'NoneType' object has no attribute 'action': The object has no animation data yet. Insert at least one keyframe before readingobj.animation_data.action, or test thatobj.animation_datais notNone.- No active object:
bpy.context.active_objectisNonewhen nothing is active. This happens most often when a script runs from the command line without selecting anything. - Keys all hold the same value: You inserted several keyframes without changing the property between calls. Assign a new value before each insert.
- Wrong frame range: Changing
frame_enddoes not remove keys outside the range. Keys beyond it still exist but will not play back. - Keys at fractional frames: Passing a float such as
12.5is allowed and creates a key between frames. Pass whole numbers unless you want that.
Exercises
Exercise
A script sets obj.location.z = 5.0 and then calls obj.keyframe_insert(data_path="location", frame=10). The playhead is at frame 1. What value does the keyframe at frame 10 store for Z, and does the playhead move?
Show answer
The keyframe stores Z = 5.0, because keyframe_insert records the property's current value. The playhead stays at frame 1, because the frame argument only chooses where the key is placed.
Exercise
Write the lines that key only the X scale of the active object at frame 1 and frame 30, with values 1.0 and 2.5, and then make all of its keys constant.
Show answer
Use index=0 on scale, then loop over the F-curves:
obj = bpy.context.activeobject
obj.scale.x = 1.0
obj.keyframeinsert(datapath="scale", index=0, frame=1)
obj.scale.x = 2.5
obj.keyframeinsert(datapath="scale", index=0, frame=30)
for fcurve in obj.animationdata.action.fcurves:
for kp in fcurve.keyframe_points:
kp.interpolation = 'CONSTANT'