我使用turtle模块在python中创建了两只乌龟,分别为“tur1”和“tur2”。我已经在屏幕上创建了事件侦听器。我创建了一个函数“move_fwd(turte_name)”,它将乌龟向前移动 20 步。
我希望如果按下“w”键,那么这个方法应该由“tur1”调用,并且 tur1 应该移动,如果按下“i”键,那么这个函数应该由“tur2”乌龟调用,并且它应该移动。
我不知道如何在 event_listener 调用此方法时传递参数“turtle_name”。
from turtle import Turtle, Screen
screen = Screen()
tur1 = Turtle()
tur1.shape("turtle")
tur1.shape("turtle")
tur1.penup()
tur1.setposition(x=-200, y=-100)
tur2 = Turtle()
tur2.shape("turtle")
tur2.penup()
tur2.setposition(x=200, y=100)
def move_fwd(turtle_name):
turtle_name.forward(20)
screen.listen()
screen.onkey(move_fwd, "w") # how to tell that this is to be called for tur1
screen.onkey(move_fwd, "i") # how to tell that this is to be called for tur2
screen.exitonclick()
你只需要调用两个不同的函数:
def move_fwd1():
tur1.forward(20)
def move_fwd2():
tur2.forward(20)
...
screen.onkey(move_fwd1, "w") # how to tell that this is to be called for tur1
screen.onkey(move_fwd2, "i") # how to tell that this is to be called for tur2