15
$\begingroup$

I'm just starting to learn scripting in Blender with Python. I made a simple operator following the quickstart intro on the Blender documentation:

import bpy

def main(context):
    for ob in context.scene.objects:
        print(ob)

class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        main(context)
        return {'FINISHED'}

def register():
    bpy.utils.register_class(SimpleOperator)

def unregister():
    bpy.utils.unregister_class(SimpleOperator)

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.simple_operator()

It then says

Once this script runs, SimpleOperator is registered with Blender and can be called from the operator search popup or added to the toolbar.

But how do I add it to the toolbar?

$\endgroup$
0

2 Answers 2

11
$\begingroup$

To add it it to the toolbar, simply have your class inherit from bpy.types.Panel, and call the class functions, the key one being draw(). You choose a space_type, a region_type and the context in which the panel should be shown.

You can also reference the example below the one you are using. BlenderCookie also has a tutorial that covers this.

See the modified code

import bpy

class SimplePanel(bpy.types.Panel):
    bl_id_name = "object.simple_operator"
    bl_space_type = "VIEW_3D"
    bl_region_type = "TOOLS"
    bl_context = "objectmode"
    bl_label = "Simple Panel"

    def draw(self, context):
        layout = self.layout
        col = layout.column(align=True)

        col.label(text="Objects in the scene:")

        col2 = layout.column(align=True)
        for ob in context.scene.objects:
            col2.label(text=str(ob.name))

def register():
    bpy.utils.register_class(SimplePanel)

def unregister():
    bpy.utils.unregister_class(SimplePanel)

if __name__ == "__main__":
    register()

enter image description here

$\endgroup$
10
$\begingroup$

After the operator already registered, all you need now is to add one more class that inherits from bpy.types.Panel

Example

class SimpleOperatorVisibility(bpy.types.Panel):
    bl_label = "Simple Operator"
    bl_space_type = "VIEW_3D"
    bl_region_type = "TOOLS"

    def draw (self, context):
        layout=self.layout

        col=layout.column()
        col.operator("object.simple_operator", text="Simple Operator")

Add those lines after class SimpleOperator and before defining register().

$\endgroup$

You must log in to answer this question.

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