【Blender Python】blender 增加 Operator
示例一
import bpy
class HelloWorldOperator(bpy.types.Operator):
bl_idname = "wm.hello_world"
bl_label = "Minimal Operator"
def execute(self, context):
print("Hello World")
return {'FINISHED'}
# Only needed if you want to add into a dynamic menu.
def menu_func(self, context):
self.layout.operator(HelloWorldOperator.bl_idname, text="Hello World Operator")
# Register and add to the view menu (required to also use F3 search "Hello World Operator" for quick access).
bpy.utils.register_class(HelloWorldOperator)
bpy.types.VIEW3D_MT_view.append(menu_func)
# Test call to the newly defined operator.
bpy.ops.wm.hello_world()
示例二
import bpy
class SimpleMouseOperator(bpy.types.Operator):
""" This operator shows the mouse location,
this string is used for the tooltip and API docs
"""
bl_idname = "wm.mouse_position"
bl_label = "Invoke Mouse Operator"
x: bpy.props.IntProperty()
y: bpy.props.IntProperty()
def execute(self, context):
# rather than printing, use the report function,
# this way the message appears in the header,
self.report({'INFO'}, "Mouse coords are %d %d" % (self.x, self.y))
return {'FINISHED'}
def invoke(self, context, event):
print("INVOKE is invoked!!!")
self.x = event.mouse_x
self.y = event.mouse_y
return self.execute(context)
# Only needed if you want to add into a dynamic menu.
def menu_func(self, context):
self.layout.operator(SimpleMouseOperator.bl_idname, text="Simple Mouse Operator")
# Register and add to the view menu (required to also use F3 search "Simple Mouse Operator" for quick access)
bpy.utils.register_class(SimpleMouseOperator)
bpy.types.VIEW3D_MT_view.append(menu_func)
# Test call to the newly defined operator.
# Here we call the operator and invoke it, meaning that the settings are taken
# from the mouse.
bpy.ops.wm.mouse_position('INVOKE_DEFAULT')
# Another test call, this time call execute() directly with pre-defined settings.
bpy.ops.wm.mouse_position('EXEC_DEFAULT', x=20, y=66)
这种的INVOKE_DEFAULT
和 EXEC_DEFAULT
调用方式 有两种:
- 一种是invoke 的 间接调用
>>> bpy.ops.wm.mouse_position("INVOKE_DEFAULT")
INVOKE is invoked!!!
信息: Mouse coords are 475 135
{'FINISHED'}
- 另一种是 exec 的直接调用
>>> bpy.ops.wm.mouse_position()
信息: Mouse coords are 0 0
{'FINISHED'}
>>> bpy.ops.wm.mouse_position("EXEC_DEFAULT")
信息: Mouse coords are 0 0
{'FINISHED'}
>>> bpy.ops.wm.mouse_position("EXEC_DEFAULT", x = 100, y = 200)
信息: Mouse coords are 100 200
{'FINISHED'}