同时查看多个实例

问题描述 投票:0回答:1

在海龟图形中,我有一张具有相同名称的一个类的多个实例的表。 我想在屏幕上以不同的方式显示这些实例,但我不知道如何。 我总是只得到一个而不是全部。

from turtle import Turtle, Screen
screen = Screen()
turtle = Turtle("square")
turtle.color("red")
list_turtle = [turtle,turtle,turtle,turtle,turtle,]
list_turtle[0].forward(20)
x = list_turtle[0].xcor() 
y = list_turtle[0].ycor()
list_turtle[1].goto(x+60,y+20)
screen.exitonclick()
    
python turtle-graphics pyhook
1个回答
0
投票

您没有多个同名实例。

列表不会增加其对象。它存储引用这些对象的地址(所谓的指针)。

可以将其想象为将您朋友的电话号码复制 10 次到列表中。然后您拨打每个电话号码并发出订单。你并不是突然拥有十个朋友,而是一个执行你所有命令的朋友。

您需要使用以下方法分别实例化每只乌龟

a_new_turtle = Turtle()

您可以使用一个函数来为您执行此操作(请参阅我的解决方案)。我给海龟设置了不同的颜色,以便在屏幕上更好地区分它们。

from turtle import Turtle, Screen

screen = Screen()
def make_turtle(form: str = "square", color='red'):
    turtle = Turtle(form) # this line makes a new instance of class "Turtle", a new turtle is generated here
    turtle.color(color)
    return turtle

# turtle instances are now made in the list
list_turtle = [make_turtle(color='blue'), make_turtle(color='green'), make_turtle(), make_turtle(), make_turtle(), ]
list_turtle[0].forward(20)
x = list_turtle[0].xcor()
y = list_turtle[0].ycor()
list_turtle[1].goto(x + 60, y + 20)
screen.exitonclick()
© www.soinside.com 2019 - 2024. All rights reserved.