Python Turtle中fillcolor传RGB值触发bad color sequence错误求助
Python Turtle fillcolor() RGB值报错的解决方法
问题原因
Python Turtle默认采用小数RGB模式,即RGB值需传入0.0到1.0之间的浮点数。你传入的(20,75,153)是0-255范围的整数,不符合默认模式的要求,因此触发TurtleGraphicsError: bad color sequence错误。
你的书籍说明中显示可以使用三个整数RGB值,是因为书籍默认已开启了0-255的颜色模式,但你当前代码缺少这一配置步骤。
解决方案
在创建Screen对象后,添加一行代码启用0-255范围的RGB颜色模式:
screen.colormode(255)
修改后的完整代码:
from turtle import Turtle,Screen from random import randint def hexagon(t, length): """Draws a hexagon with the given length.""" for count in range(6): t.forward(length) t.left(60) def radialPattern(t, n, length, shape): """Draws a radial pattern of n shapes with the given length.""" for count in range(n): shape(t, length) t.left(360 / n) screen = Screen() #create a screen object screen.colormode(255) # 启用0-255 RGB颜色模式 screen.setup(width=600,height=400) #size screen.bgcolor("lightblue") screen.title("My turtle") t = Turtle() #added code here: t.fillcolor(20,75,153) t.begin_fill() radialPattern(t,5,30,hexagon) t.end_fill() screen.exitonclick() #keep the screen open until user closes it
其他可选方案
如果你不想修改颜色模式,也可以将RGB值转换为0-1之间的小数:
t.fillcolor(20/255, 75/255, 153/255)
内容的提问来源于stack exchange,提问作者Spellbinder2050
相关产品推荐
相关产品推荐

