I need to add a draw handler when starting blender. problem is that handler uses context data for drawing. because of this, an error occurs when adding handler in addon register() function:

enter image description here

I found out that such an error happens due to the use of context during the registration of the addon. I do not know any other automation methods other than addon registration, so I will be happy to listen to your suggestions

  • 1
    $\begingroup$ i recommend describing what you want to achieve. I honestly don't understand what your (end) goal is. And if you have problems with your code, you should at least provide a runnable example so that we can check it out. thx. $\endgroup$
    – Chris
    Aug 1, 2023 at 7:23

1 Answer 1


You can't add draw handler in register() function in your addon, because it runs too early.

Use bpy.app.handlers instead

bl_info = {
    "name" : "Add draw handler to Viewport when start",
    "author" : "me",
    "version" : (23, 8, 1),
    "blender" : (3, 4),
    "location" : "View3d > Tool",
    "warning" : "",
    "description" : "Test",
    "wiki_url" : "",
    "category" : "3D View",

#### copy from https://docs.blender.org/api/3.6/gpu.html
import bpy
import gpu
from gpu_extras.batch import batch_for_shader

vertices = (
    (100, 100), (300, 100),
    (100, 200), (300, 200))

indices = (
    (0, 1, 2), (2, 1, 3))

shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices)

def draw():
    shader.uniform_float("color", (0, 0.5, 0.5, 1.0))

from bpy.app.handlers import persistent

def when_version_update_end(dummy):
    bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL')

def register():

def unregister():
    bpy.types.SpaceView3D.draw_handler_remove(draw, 'WINDOW')

if __name__ == "__main__":
  • $\begingroup$ Smart. I guess you use version_update because it runs once on load ? Have you considered load_post ? I'm not sure version_update runs if the blend version and your blender version are the same. Or if it does I'm not sure it should blender.stackexchange.com/questions/233720/… $\endgroup$
    – Gorgious
    Aug 1, 2023 at 8:31
  • $\begingroup$ load_post also works, but it runs again when you open a new blend file and version_update doesn't. $\endgroup$
    – X Y
    Aug 1, 2023 at 8:46
  • $\begingroup$ And I tested that version_update trigger when your addon is installed in different blender versions. $\endgroup$
    – X Y
    Aug 1, 2023 at 8:56

You must log in to answer this question.

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