We can bind not only common system operators to buttons on the toolbar (T-Panel), but also custom ones created by us. The principle of connection in Blender Python API is the same for both system and custom operators.
For example, let’s define a custom operator that adds a UV Sphere to the scene at a random location between 0 and 10.
1 2 3 4 5 6 7 8 9 10 |
class TEST_OT_test(bpy.types.Operator): bl_idname = 'test.test' bl_label = 'TEST' bl_options = {'REGISTER'} def execute(self, context): bpy.ops.mesh.primitive_uv_sphere_add( location=(random.uniform(0, 10), random.uniform(0, 10), random.uniform(0, 10)) ) return {'FINISHED'} |
Inside the execute() function, we call the operator for adding a sphere to the scene, specifying random coordinates from 0 to 10 in the “location” parameter, but here you can type any code you need.
Register our custom operator in the Blender API.
1 |
bpy.utils.register_class(TEST_OT_test) |
Next, define a class for the tool and its button in the T-panel.
1 2 3 4 5 6 7 8 9 |
class TestTool(bpy.types.WorkSpaceTool): bl_space_type = 'VIEW_3D' bl_context_mode = 'OBJECT' bl_idname = 'test_tool.test_tool_select' bl_label = 'Call user operator' bl_icon = 'ops.mesh.primitive_sphere_add_gizmo' bl_keymap = ( ('test.test', {'type': 'LEFTMOUSE', 'value': 'CLICK'}, None), ) |
The most important thing for us here is the “bl_keymap” tuple, in which we specify the binding of operators to this tool, and assign the conditions for their execution.
Our “bl_keymap” has only one element, also a tuple consisting of three elements. The first element – here we specify the “bl_idname” of our operator, we defined earlier. The second element specifies the action by which the operator will be executed – a left mouse click. The third element is used to pass parameters to the operator, we don’t need it now, so we set it to None.
Register our tool class in the Blender Python API.
1 |
bpy.utils.register_tool(TestTool, after={'builtin.scale_cage'}, separator=True, group=True) |
And force a redraw of all areas so that our new tool button is immediately drawn.
1 2 |
for area in bpy.context.screen.areas: area.tag_redraw() |
Now, when our TestTool tool is active (selected) in the toolbar and the user left-clicks on the viewport, our custom “test.test” operator will be called with each click, which will result in a UV Sphere being added to the scene area with coordinates from 0 to 10.