属性错误:'Turtle'对象没有'colormode'属性。但是我的代码有。

3
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()

我正在尝试使用随机漫步生成随机颜色,但是出现了这个错误。
2个回答

3
我不同意目前两种不同的“import turtle”答案。问题在于colormode是一个screen(单例)实例方法,而不是一个turtle实例方法。
from turtle import Turtle, Screen
from random import randint, choice

DIRECTIONS = [0, 90, 270, 180]

def random_color():
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)
    random_color = r, g, b

    return random_color

screen = Screen()
screen.colormode(255)

turtle = Turtle()
turtle.speed('fastest')

for _ in range(200):
    turtle.color(random_color())
    turtle.forward(30)
    turtle.setheading(choice(DIRECTIONS))

screen.exitonclick()

你可以直接通过导入turtle来访问初学者友好的全局colormode函数(这就是为什么其他答案有效),但是当你选择通过显式导入Screen和Turtle来使用对象API时,为什么要这样做呢?
有些模式是特定于海龟的,例如radians,可以在海龟实例上调用。但是其他模式适用于整个海龟环境,例如colormode,需要在屏幕实例上调用。如果不查看文档,往往不清楚哪些是哪些。

非常感谢您,先生。我真的对此非常担心,因为我以为我的电脑出了问题,哈哈。 - undefined
你说得对——我已经更新了我的回答,让它更加清晰明了。 - undefined

2

turtle = Turtle() 创建了一个海龟的实例(一个单独的海龟)。这与turtle模块本身不同,通常作为import turtle导入。

colormodeScreen()单例实例上的一个函数,在turtle模块上作为顶级函数的别名,而不是在Turtle()实例上。

您可以在turtle模块本身或Screen上访问colormode

另外,random_colour是一个拼写错误。我建议避免使用额外的变量,直接return r, g, b

我还使用了Black对您的代码进行了格式化,我建议您在所有代码中都使用它,以便其他程序员能够轻松阅读。

import random
from turtle import Screen, Turtle


turtle = Turtle()
screen = Screen()
screen.colormode(255)


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


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.exitonclick()

顺便说一下,如果你的编辑器没有自动补全功能,你可以使用dir()来查找对象上可用的方法:
>>> import turtle
>>> "colormode" in dir(turtle)
True
>>> "colormode" in dir(Screen())
True
>>> "colormode" in dir(turtle.Turtle())
False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接