为什么我用这个rgb代码收到错误?

时间:2016-10-26 07:03:20

标签: python raspberry-pi rgb

我正在编写一个在Raspberry Pi Sensehat上运行的程序。我写了这段代码:

from time import gmtime, strftime
from random import randint
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
def hilo(a, b, c):
    if c < b: b, c = c, b
    if b < a: a, b = b, a
    if c < b: b, c = c, b
    return a + c
def complement(r, g, b):
    k = hilo(r, g, b)
    return tuple(k - u for u in (r, g, b))
while True:
    r=randint(0, 255)
    g=randint(0, 255)
    b=randint(0, 255)
    while True:
        x, y, z = sense.get_accelerometer_raw().values()
        x = abs(x)
        y = abs(y)
        z = abs(z)
        sense.show_message(strftime('%H:%M', gmtime()), scroll_speed= 0.05, text_colour=[r, g, b], back_colour=[complement(r, g, b)])
        if x > 2 or y > 2 or z > 2 :
            break
    else:
         continue

我收到此错误消息:

Traceback (most recent call last):
  File "/home/pi/Desktop/Bill's stuff/billrclock2-0*UNFINISHED*.py", line 23, in <module>
    sense.show_message(strftime('%H:%M', gmtime()), scroll_speed= 0.05, text_colour=[r, g, b], back_colour=[complement(r, g, b)])
  File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 449, in show_message
     self.set_pixels(coloured_pixels[start:end])
  File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 269, in set_pixels
    raise ValueError('Pixel at index %d is invalid. Pixels must contain 3 elements: Red, Green and Blue' % index)
ValueError: Pixel at index 0 is invalid. Pixels must contain 3 elements: Red, Green and Blue

我注意到它说像素必须包含3个元素:r,g,b&#39;但在这种情况下,像素确实包含r,g和b。为什么会这样?谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

documentation表示两种颜色都应该是三项列表。

您正在传递一个项目列表,该列表恰好包含一个3项元组。

解决此问题的简单方法是将补码方法的结果转换为列表。

您可以通过两种方式实现,方法本身:

def complement(r, g, b):
    k = hilo(r, g, b)
    return [k - u for u in (r, g, b)]

# .. later down

sense.show_message(strftime('%H:%M', gmtime()),
                   scroll_speed= 0.05,
                   text_colour=[r, g, b],
                   back_colour=complement(r, g, b))

或者您可以将结果转换为列表:

def complement(r, g, b):
    k = hilo(r, g, b)
    return tuple(k - u for u in (r, g, b))

sense.show_message(strftime('%H:%M', gmtime()),
                       scroll_speed= 0.05,
                       text_colour=[r, g, b],
                       back_colour=list(complement(r, g, b)))