I have been trying to write script that with a button it will open a file browser to choose an image file, then use it to create a new material then add it to the selected object (plane) as a texture.

class Button_UploadImage(bpy.types.Operator):
bl_idname = "object.upload_image"
bl_label = "Upload Image"
def execute(self, context):
    obj = bpy.context.object
    # Prompt the user to select an image file
    image = bpy.ops.image.open('INVOKE_DEFAULT')
    # Create a new material
    material = bpy.data.materials.new(name="My Material")

    # Assign the material to the object

    # Assign the image to the material
    < What to put here ? >
    return {'FINISHED'}

I also tried to get bpy.ops.import_image.to_plane from the Images as Planes Addon to work but with no luck.

  • $\begingroup$ image = bpy.ops.image.open('INVOKE_DEFAULT') this is wrong since operators return a set of strings (in your example {'FINISHED'}), never the object that is operated on. You might want to explore the "operator file import" template available in the header of the script editor in blender. $\endgroup$
    – Gorgious
    Jan 3, 2023 at 14:43

1 Answer 1


You need to make the newly created material "Use Nodes" and then load the image into an image texture node. Try the following code (please note the material variable is "mat")

mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
texImage.image = bpy.data.images.load("C:/Users/Dell/Desktop/blenderwork/randomColors.png")
mat.node_tree.links.new(bsdf.inputs['Base Color'], texImage.outputs['Color'])
if obj.data.materials:
    obj.data.materials[0] = mat


However there was another error that I encountered, when the file open dialog box was open, the rest of the code ran without waiting for the file dialog to return any value. Once you get the above code running, you might need to address this as well.


You must log in to answer this question.

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