run python script with button

Can i run python script via button in view3d panel
What should I write( syntax)

Here it is.


import bpy


class MyOperator(bpy.types.Operator):
    """This is my simple operator"""
    bl_idname = "scene.myoperator"
    bl_label = "My Operator"
    
    def execute(self, context):
        print("Hello")
        return {"FINISHED"}


class MyPanel(bpy.types.Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "My Panel"
    bl_idname = "SCENE_PT_layout"




    def draw(self, context):
        layout = self.layout
        row = layout.row()
        row.operator("scene.myoperator")


bpy.utils.register_class(MyOperator)
bpy.utils.register_class(MyPanel)

thanks const very helpfull

Thanks, for further information have a look at the Python templates in the Text Editor toolbar. Also if you see something you find interesting in the GUI do a right click and then “Edit Source” to investigate it.

instead of “print(“hello”)” I can’t use something like “bpy.ops.mesh.primitive_cube_add()”. Why? How can I use this kind of comand in Operators?

You simply substitute that line with the operator you want to use:


import bpy




class MyOperator(bpy.types.Operator):
    """This is my simple operator"""
    bl_idname = "scene.myoperator"
    bl_label = "My Operator"
    
    def execute(self, context):
        bpy.ops.mesh.primitive_cube_add()
        return {"FINISHED"}




class MyPanel(bpy.types.Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = "My Panel"
    bl_idname = "SCENE_PT_layout"








    def draw(self, context):
        layout = self.layout
        row = layout.row()
        row.operator("scene.myoperator")




bpy.utils.register_class(MyOperator)
bpy.utils.register_class(MyPanel)

This works for me, having an operator run another operator.


import bpy


class MyOperator(bpy.types.Operator):
    """This is my simple operator"""
    bl_idname = "scene.myoperator"
    bl_label = "My Operator"
    
    def execute(self, context):
        print("Hello")
        bpy.ops.mesh.primitive_cube_add()
        return {"FINISHED"}


bpy.utils.register_class(MyOperator)


# test call
bpy.ops.scene.myoperator()
#

tks const!
Jeffo Granetto

what is this line doing, I can not find it in the api.
bl_idname = "SCENE_PT_layout"

my question is based on the following example:

properties_material.py

this script that is integrated in your blender 2.79 that generates the GUI in the properties area does not have nor present this line in any part of the script, also what I observe is that it declares the class first