How to use node_tree.nodes.add_node(“ShaderNodeTexImage”)

I’m brand new at scripts in Blender and am struggling to get over my first hurdle. Going mad with almost-but-not-quite script lines from around BA and StackExchange. Hopefully somebody will take pity on me …

All I want to do is add an image texture node to the active object (it has a node-based material already). In the node window I can use shift-A / Texture / Image Texture

The python tip that comes up says bpy.ops.node.add_node(type=“ShaderNodeTexImage”,…). So I tried this script:

import bpy

bpy.context.scene.object.active
bpy.ops.node.add_node(type=“ShaderNodeTexImage”)

Which doesn’t work.

I realise this is embarrassingly simple, but I’m going crazy trying to work it out!

Thanks in advance.

The add_node operator needs the NodeEditor context to run. So you cannot call it from outside the Node Editor.

What you can do is:

import bpy

mat = bpy.context.scene.objects.active.active_material
image_node = mat.node_tree.nodes.new('ShaderNodeTexImage')

(this is for 2.79)

That’s great, thanks a lot.

I’m using 2.80 (seems like the right time to embrace it), so thanks to this post I’m now using:

import bpy

mat = bpy.context.view_layer.objects.active.active_material
image_node = mat.node_tree.nodes.new('ShaderNodeTexImage')

Which seems to do the trick. Over my first hurdle! Thanks again Secrop.