2
$\begingroup$

I am creating a simple add-on in Blender. Initially I tested the code in Python console, then I wrapped it in an operator and added it to Object menu, it worked well:

class MyOperator(bpy.types.Operator):
    bl_idname = 'object.MyOperator'
    bl_label = 'MyOperator'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        # ...affairs...
        return {'FINISHED'}


def task_func(self, context):
    self.layout.operator(MyOperator.bl_idname)


def register():
    bpy.utils.register_class(MyOperator)
    bpy.types.VIEW3D_MT_object.append(task_func)

But now I need to add several operators and a submenu. I tried this example, and but it is not working:

class MyMenu(bpy.types.Menu):
    bl_idname = 'object.MyMenu'
    bl_label = 'MyMenu'

    def draw(self, context):
        layout = self.layout
        layout.operator(MyMenu.bl_idname, text=MyMenu.bl_label)


def menu_func(self, context):
    # None of these is working :(
    self.layout.call_menu(name=MyMenu.bl_idname)
    self.layout.menu(MyMenu.bl_idname)


def register():
    bpy.utils.register_class(MyOperator)
    bpy.types.VIEW3D_MT_object.append(menu_func)

So, what's the problem about? How can I solve it?

$\endgroup$
3
$\begingroup$

There were a number of issues. From not registering menu class and having invalid bl_idname's (no capital letters)

Here is working code. In 2.8 it is a requirement that class names reflect the bl_idname.

import bpy

class OBJECT_OT_myoperator(bpy.types.Operator):
    bl_idname = 'object.myoperator'
    bl_label = 'MyOperator'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        # ...affairs...
        return {'FINISHED'}

class OBJECT_MT_mymenu(bpy.types.Menu):
    bl_idname = 'object.mymenu'
    bl_label = 'MyMenu'

    def draw(self, context):
        layout = self.layout
        layout.operator(OBJECT_OT_myoperator.bl_idname)

def menu_func(self, context):
    self.layout.menu(OBJECT_MT_mymenu.bl_idname)

def register():
    bpy.utils.register_class(OBJECT_OT_myoperator)
    bpy.utils.register_class(OBJECT_MT_mymenu)
    bpy.types.VIEW3D_MT_object.append(menu_func)

def unregister():
    bpy.utils.unregister_class(OBJECT_OT_myooperator)
    bpy.utils.unregister_class(OBJECT_MT_mymenu)
    bpy.types.VIEW3D_MT_object.remove(menu_func)

if __name__ == "__main__":
    register()
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.