为什么字典查找会导致 'unhashable type' 错误,但使用直接值却不会?

Why is Dictionary lookup causing 'unhashable type' error, but using direct values doesn't?

我正在尝试使用字典查找而不是使用繁琐的多个 if 语句来改进一些代码。但是,当我尝试 运行 使用变量的代码派生代码 returns 一个“TypeError: unhashable type”,但是如果我 运行 相同的代码而是使用直接值而不是派生值,代码 运行s.

这是失败的代码:

def colour_check_under_mouse():
 global d_colours
 mouse_pos = pygame.mouse.get_pos()
 if pygame.mouse.get_pressed()[0]:
    colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
    print(colour_under_mouse)
    colour_selected = d_colours[colour_under_mouse]
    # colour_selected = d_colours[255, 0, 0, 255]
    print(colour_selected)

并且在将注释掉的行替换为具有硬编码值的行之后,这是 运行s:

的代码
def colour_check_under_mouse():
 global d_colours
 mouse_pos = pygame.mouse.get_pos()
 if pygame.mouse.get_pressed()[0]:
    colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
    print(colour_under_mouse)
    # colour_selected = d_colours[colour_under_mouse]
    colour_selected = d_colours[255, 0, 0, 255]
    print(colour_selected)

使用的字典是:

d_colours = {(255, 0, 0, 255): 'Red', (0, 255, 0, 255): 'Green', (0, 0, 255, 255): 'Blue', (255, 255, 0, 255): 'Yellow'}

当我在 colour_selected = 行中硬编码与上述代码返回的值完全相同时,为什么代码 运行 成功,我感到困惑。我明白什么是不可散列的类型,但是有人可以帮助我理解两行中发生的变化导致一行导致该错误吗?干杯。

根据我在 PyGame (link) 的文档中看到的内容,您正在使用的代码部分:

pygame.Surface.get_at

returns 一种颜色而不是元组。尝试使用:

colour_under_mouse = tuple(pygame.Surface.get_at(screen, mouse_pos))