每次按 Python 中的同一个按钮时,如何按顺序更改海龟图像?

How can I change turtle images in order every time I press the same button in Python?

我想编写一个程序,每次按下 'n' 键时都会按顺序更改海龟图像。

应该先从'classic'形状开始,每按一次'n'键,改变形状为'circle'、'arrow'、[=23] =] 然后循环回到 'classic'.

import turtle
canvas = turtle . Screen ()
t = turtle . Turtle ()

def changeTurtle () :
    for n in range (1, 5) :
        if n == 1 :
            t . shape ('circle')
        elif n == 2 :
            t . shape ('arrow')
        elif n == 3 :
            t . shape ('turtle')
        elif n == 4 :
            t . shape ('classic')

t . shape ('classic') # first turtle 'classic' shape
canvas . onkey (changeTurtle, 'n') # press 'n'key

canvas . listen ()
turtle . mainloop ()

按'n'键应该有一次变了。问题是,变化太快了。

您将使用 for 循环一次遍历 n 的所有可能值。您需要做的是在函数外保存 n 的值 ,并在每次调用函数时更改它:

n = 1
def changeTurtle():
    global n
    n = (n % 4) + 1  # cycle through 1, 2, 3, 4, 1, 2, 3, 4, ...
    if n == 1:
        t.shape('circle')
    elif n == 2:
        t.shape('arrow')
    elif n == 3:
        t.shape('turtle')
    else:
        t.shape('classic')

以下是我过度设计这个问题的方法(并消除了对 global 语句的需要):

from turtle import Screen, Turtle

def changeTurtle():
    index = shapes.index(turtle.shape()) + 1
    shape = shapes[index % len(shapes)]

    turtle.shape(shape)
    screen.title(shape)

turtle = Turtle()
turtle.shapesize(3)
turtle.shape('classic')  # first turtle 'classic' shape

screen = Screen()
screen.title(turtle.shape())
shapes = screen.getshapes()

screen.onkey(changeTurtle, 'n')  # press 'n' key

screen.listen()
screen.mainloop()

您的函数的替代方法是使用一个无限迭代器(如 itertools.cycle)加载您想要循环的所有形状。当你想要下一个形状时,你的程序只是简单地请求它,改变海龟,然后继续它之前所做的任何其他事情。以下程序演示了如何完成此操作:

import itertools
import turtle


def main():
    canvas = turtle.Screen()
    t = turtle.Turtle()
    # noinspection PyProtectedMember
    shapes = itertools.cycle(sorted(canvas._shapes.keys()))
    t.shape(next(shapes))
    canvas.onkey(lambda: t.shape(next(shapes)), 'n')
    canvas.listen()
    canvas.mainloop()


if __name__ == '__main__':
    main()