python-3.x AttributeError:'Turtle'对象没有属性'colormode'但我的代码有

icnyk63a  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(244)
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()

字符串
我试图生成一个随机的颜色与随机游走,但这个错误是未来

o0lyfsai

o0lyfsai1#

我不同意目前“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函数(这就是其他答案有效的原因),但是当您通过显式导入ScreenTurtle选择对象API时,为什么要这样做呢?
有些模式是特定于turtle的,例如radians,可以在turtle示例上调用。但其他模式适用于整个turtle环境,例如colormode,需要在屏幕示例上调用。如果不查看文档,并不总是清楚哪些是哪些。

bxpogfeg

bxpogfeg2#

turtle = Turtle()创建了一个turtle的示例(单个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

相关问题