Python - Turtle - 从 Turtle 图形中获取数字表示(rgb 值、十六进制字符串)而不是颜色名称作为字符串

Python - Turtle - Get numeric representation (rgb values, hex string) instead of color name as string from Turtle graphics

我在 python 中使用 turtle 模块,我想获取颜色的数字表示(RGB、十六进制等)而不是字符串形式的名称。

from turtle import Screen
print(Screen().bgcolor())

上面的示例打印 >>> white,我需要得到一个像 >>> #FFFFFF>>> rbg(255, 255, 255) 这样的值。

我正在寻找为任意值创建互补色,因此颜色名称不够有用。

在这种情况下,我们需要深入了解并访问 turtle 所在的 tkinter:

from turtle import Screen

screen = Screen()
canvas = screen.getcanvas()
root = canvas.winfo_toplevel()

r, g, b = root.winfo_rgb(screen.bgcolor())

print(r, g, b)

输出

% python3 test.py
65535 65535 65535
% 

要将这些值传回 turtle,如果我们使用默认的 turtle 颜色模型,我们需要(浮点数)将它们除以 65535,或者将它们移动 8 位以备选 colormode(255).