更改乌龟1的位置会更改乌龟2的位置

时间:2019-05-13 05:47:47

标签: python turtle-graphics

def func():
    print("T POSITION: ", t.pos()) # prints 100, 100
    t2.pencolor("black")
    t2.setpos(0,0)
    print("T POSITION: ", t.pos()) # Now, prints 0, 0
    print("T2 POISTION: ", t2.pos())
两者。即使我分别声明为全局变量t1和t2,也将t.pos()t2.pos()设置为(0,0)

t= turtle.getturtle()
t.setpos(100,100)
t2 = turtle.getturtle().

如果我只想将t2的位置更改为0,0,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您需要copy.copy t2

import turtle,copy
t= turtle.getturtle()
t.setpos(100,100)
t2 = copy.copy(turtle.getturtle())
def func():
    print("T POSITION: ", t.pos())
    t2.pencolor("black")
    t2.setpos(0,0)
    print("T POSITION: ", t.pos())
    print("T2 POISTION: ", t2.pos())
func()

现在您得到以下结果:

T POSITION:  (100.00,100.00)
T POSITION:  (100.00,100.00)
T2 POISTION:  (0.00,0.00)

否则:

>>> t==t2
True
>>> t is t2
True
>>> id(t)
333763277936
>>> id(t2)
333763277936
>>> id(t) == id(t2)
True
>>> 

它们是相同的对象!!!完全!

答案 1 :(得分:0)

简短的回答:“不要使用getturtle()!”这不是您想要的功能。它用于访问单一的 default 乌龟,很少需要/使用。而是使用Turtle()来换一只新乌龟:

import turtle

def func():
    print("T1 POSITION: ", t1.pos())
    t2.setpos(0, 0)
    print("T1 POSITION: ", t1.pos())
    print("T2 POSITION: ", t2.pos())

t1 = turtle.Turtle()
t1.pencolor("red")
t1.setpos(100, 100)

t2 = turtle.Turtle()
t2.pencolor("green")

func()

t2.circle(100)

t2.clear()

turtle.done()

您不需要copy.copy()乌龟。如果您想要一只全新的乌龟,请使用Turtle()。如果您想要一只与现有乌龟一样的新乌龟,请在该乌龟上致电.clone(),例如t3 = t1.clone()