目录
本节课程带你了解,如何在下方的菜单中加入自定义命令。
如果你想要免费的blender插件、模型等可以看看这个blender资源库
还有免费的Blender入门教程
01 代码框架
修改 __init__.py
代码,除 bl_info 参数不变,其余的更新为以下代码:
import bpy
class menu_name(bpy.types.Operator):
bl_idname = "menu_name.aleshu_001"
bl_label = "测试菜单标签"
bl_description = "测试菜单描述"
def execute(self, context):
print("Hello World")
return {'FINISHED'}
def menu_func(self, context):
self.layout.operator(menu_name.bl_idname, text="测试菜单文本")
classes = (
menu_name,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.TOPBAR_MT_file.append(menu_func)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.TOPBAR_MT_file.remove(menu_func)
if __name__ == "__main__":
register()
想要在菜单中加入一个自定义命令,你必须要满足几个要求:
-
注册一个Operator类(bpy.types.Operator);
-
在注册时,通过 bpy.types.TOPBAR_*.append() 新增菜单;
-
在卸载时,通过 bpy.types.TOPBAR_*.remove() 移除菜单;
-
新增/移除菜单需要调用一个 draw_func 函数。
01.01 定义 Operator 类
根据以上步骤,我们需要先定义一个 Operator 类,其中 bl_idname、bl_label、bl_description 都可以自定义。
bl_idname 必须 xx.xx 的格式,否则会报错。execute() 函数中可以执行自定义指令。
class menu_name(bpy.types.Operator):
bl_idname = "menu_name.aleshu_001"
bl_label = "测试菜单标签"
bl_description = "测试菜单描述"
def execute(self, context):
print("Hello World")
return {'FINISHED'}
01.02 注册 Operator 类
定义完成后,需要在Blender正式启用前注册类:
bpy.utils.register_class(cls)
在案例代码中,我们采用了for循环,去遍历所有类名。
当然有注册,就有卸载,在 unregister() 函数中,必须使用 bpy.utils.unregister_class(cls)
完成卸载动作。
01.03 在指定菜单列表中附加自定义命令
bpy.types.TOPBAR_MT_file.append(menu_func)
该函数可以在文件菜单最后添加一个新的命令。
其中 menu_func
是一个函数。
def menu_func(self, context):
self.layout.operator(menu_name.bl_idname, text="测试菜单文本")
01.04 效果展示
02 菜单位置
若我们想要在不同的菜单列表中添加自定义命令,就需要了解每一个菜单对应的参数。
将上述框出来的代码替换成下面的参数即可更换菜单的位置。
-
bpy.types.TOPBAR_MT_editor_menus
-
bpy.types.TOPBAR_MT_blender
-
bpy.types.TOPBAR_MT_blender_system
-
bpy.types.TOPBAR_MT_file
-
bpy.types.TOPBAR_MT_file_new
-
bpy.types.TOPBAR_MT_file_previews
-
bpy.types.TOPBAR_MT_file_recover
-
bpy.types.TOPBAR_MT_file_import
-
bpy.types.TOPBAR_MT_file_export
-
bpy.types.TOPBAR_MT_file_external_data
-
bpy.types.TOPBAR_MT_file_cleanup
-
bpy.types.TOPBAR_MT_file_defaults
-
bpy.types.TOPBAR_MT_edit
-
bpy.types.TOPBAR_MT_render
-
bpy.types.TOPBAR_MT_window
-
bpy.types.TOPBAR_MT_help