1
$\begingroup$

I am trying to add materials via python (which I am new to) but I can not even get copy and pasted code from here to work. colorsys is imported and I'm using Blender 2.91.

    mat = bpy.data.materials.new(name='Material ({0:0>2d}, {1:0>2d})'.format(k, j))
    mat.diffuse_color = colorsys.hsv_to_rgb(normdist, 0.875, 1.0)
    current.data.materials.append(mat)
    

ValueError: bpy_struct: item.attr = val: sequences of dimension 0 should contain 4 items, not 3.

I have tried:

mat.diffuse_color = colorsys.hsv_to_rgb(normdist, .5, 0.875, 1.0)

TypeError: hsv_to_rgb() takes 3 positional arguments but 4 were given


mat.diffuse_color = colorsys.hsv_to_rgb(.5, 0.875, 1.0)

ValueError: bpy_struct: item.attr = val: sequences of dimension 0 should contain 4 items, not 3


mat.diffuse_color = colorsys.hsv_to_rgb(.5, 0.875, 0.9, 1.0) 

crashes Blender


mat.diffuse_color =  random(), random(), random()

NameError: name 'random' is not defined

nothing is working!

$\endgroup$

1 Answer 1

2
$\begingroup$

TypeError: hsv_to_rgb() takes 3 positional arguments but 4 were given This error means the function expects 3 values, but you're giving it 4, so it throws an error.

ValueError: bpy_struct: item.attr = val: sequences of dimension 0 should contain 4 items, not 3. This error tells you that the property expects a sequence of 4 items assigned to it, not 3. This is because diffuse_color holds 4 values: R, G, B and A for Alpha. However, the colorsys.hsv_to_rgb() returns only 3 values, as the function name suggests and as the console displays:

>>> colorsys.hsv_to_rgb(.5, 0.875, 1.0)
(0.125, 1.0, 1.0)

In order to have a sequence compatible with the Blender's property, you have to add the alpha value to that sequence:

mat.diffuse_color = colorsys.hsv_to_rgb(.5, 0.875, 1.0) + (1.0,)

notice the awkward comma in the parentheses - without it Python would confuse it with a float wrapped around in parentheses like in mathematical equations. You only need such awkward comma in single-element tuples.

$\endgroup$
1
  • $\begingroup$ Wow thank you so much. Figuring out how to add the alpha value like that would have been so confusing on my own. $\endgroup$
    – mig
    Feb 8, 2021 at 6:58

You must log in to answer this question.

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