AttributeError:“Turtle”对象没有属性“colormode”,但我的代码有

问题描述 投票:0回答:1
from turtle import Turtle, Screen
import random

turtle = Turtle()
turtle.colormode(255)

def random_color():
  r = random.randint(0,255)
  g = random.randint(0,255)
  b = random.randint(0,255)
  random_colour= (r,g,b)
  return random_color

direction = [0,90,270,180]
turtle.speed(0)
# Remove the `where` variable since it is not used.

# Add a colon (`:`)` after the `for` loop to indicate the beginning of the loop body.
for _ in range(200):
  turtle.color(random_color())
  turtle.forward(30)
  turtle.setheading(random.choice(direction))

# Move the `screen.exitonclick()` function to the end of the code snippet so that the screen does not close until the user clicks it.
screen = Screen()
screen.exitonclick()

我试图通过随机游走生成随机颜色,但这个错误即将到来

python python-3.x turtle-graphics python-turtle
1个回答
0
投票

您收到此错误是因为您正在通过以下方式创建海龟对象:

turtle = Turtle()

然后做:

turtle.colormode(255)

你将会得到

AttributeError: 'Turtle' object has no attribute 'colormode'

你必须直接使用turtle模块进行颜色模式,而不需要创建对象

import turtle
from turtle import Turtle, Screen
import random

turtle.colormode(255)


def random_color():
  r = random.randint(0,255)
  g = random.randint(0,255)
  b = random.randint(0,255)
  random_colour= (r,g,b)
  return random_color  
© www.soinside.com 2019 - 2024. All rights reserved.