how to change frame?

i need to switch to a new frame then add a keyframe on that frame, the only thing i could find to do that was

bpy.ops.anim.change_frame(frame=10, snap=False)

However this fails with:

RuntimeError: Operator bpy.ops.anim.change_frame.poll() Expected an timeline/ani
mation area to be active
Error: Python script fail, look in the console for now…

Is there any alternative? or a way to make the viewport the active window?


If drivers, constraints and other animation stuff doesn’t need to be updated with a frame change, you might also want to use
bpy.context.scene.frame_current = … in rare occasions.

If you want to insert a keyframe, then there are a couple ways to do so.
The easiest is probably to set the property you want to animate, then call e.g.

bpy.context.object.keyframe_insert(“location”, frame=…)

But you can do that more low level too (which isn’t necessary unless you plan to insert thousands of keyframes).

Read here:

Thanks, that worked