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())
两者皆有。
t.pos()
和 t2.pos()
设置为 (0,0)
,即使我分别声明为全局变量 t1 和 t2 。
t= turtle.getturtle()
t.setpos(100,100)
t2 = turtle.getturtle().
如果我只想将
t2
的位置更改为0,0
,我该如何实现呢?
您需要
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
>>>
它们是相同的物体!完全可以!
简短的回答,“不要使用
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()
。