1
$\begingroup$

I've been trying to add an empty keyframe to a grease pencil object using bpy.ops.gpencil.blank_frame_add but I just can't make it work.

import bpy

bpy.ops.object.gpencil_add(align='WORLD', location=(0, 0, 0), scale=(1, 1, 1), type='EMPTY')
bpy.ops.gpencil.blank_frame_add(all_layers=True)

When I use the context menu draw>animation>Insert Blank Keyframe it works as it should, I only can't get it to work using the script.

What am I doing wrong?

Thanks!

$\endgroup$
2
  • $\begingroup$ what kind of error message do you have while trying to do so ? I bet it's because you're using bpy.ops (which is a bad habit) and you will need to override the context. You'd better go for avoiding the use of operators and look at object.data.layers[i].frames.new(frame_number) $\endgroup$
    – Tomreggae
    Feb 8, 2022 at 16:31
  • $\begingroup$ Hi @Tomreggae , thanks for looking into it! There's no error whatsoever, that's what confuses me. Similar operators like bpy.ops.gpencil.active_frame_delete() in the same structure work just fine. I've heard the bad habit part already, but as I am very new to scripting in Blender I started simple and dirty. Thank you for the suggestion, I'll try to dig deeper. $\endgroup$
    – mana
    Feb 8, 2022 at 22:04

1 Answer 1

2
$\begingroup$

When calling an operator from script, you need to override the context. But calling operators (bpy.ops) with python is generally a bad idea and you should access data trough bpy.data instead.

Here is the way to add new keyframes, you should find a similar way for creating new object.

import bpy
object = bpy.context.object #picking an object (the active one ?)

gp_object = object.data  #accessing its data
for layer in gp_object.layers :
    layer.frames.new(bpy.context.scene.frame_current) #the new() function needs a frame_number attribute , in this case, the current frame.
$\endgroup$
2
  • $\begingroup$ My sincere thanks!! That is exactly what I was looking for. $\endgroup$
    – mana
    Feb 11, 2022 at 10:00
  • 1
    $\begingroup$ Footnote: Calling bpy operators is not generally a bad idea, although you can find thousands of posts that say so. It is a bad idea to call bpy.ops functions in a situation where it will affect performance or when there is a cleaner way to do it without the ops. It is a good idea to call bpy.ops when doing so does not create a performance issue and the alternatives result in more difficult to understand code., $\endgroup$ Feb 14, 2022 at 0:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .