Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在每次按下Python中的相同按钮时按顺序更改海龟图像?_Python_Turtle Graphics - Fatal编程技术网

如何在每次按下Python中的相同按钮时按顺序更改海龟图像?

如何在每次按下Python中的相同按钮时按顺序更改海龟图像?,python,turtle-graphics,Python,Turtle Graphics,我想写一个程序,每次按“n”键时,按顺序更改海龟图像 它应该首先以“经典”形状开始,每次按下“n”键时,将形状更改为“圆圈”、“箭头”、“海龟”,然后循环回“经典” import turtle canvas = turtle . Screen () t = turtle . Turtle () def changeTurtle () : for n in range (1, 5) : if n == 1 : t . shape ('circle'

我想写一个程序,每次按“n”键时,按顺序更改海龟图像

它应该首先以“经典”形状开始,每次按下“n”键时,将形状更改为“圆圈”、“箭头”、“海龟”,然后循环回“经典”

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')

下面是我如何对这个问题进行过度设计(并消除对
全局
声明的需要):


函数的另一种选择是使用一个无限迭代器(如
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()

您的问题是,它会在一次按键时通过所有变体进行更改,还是会在按键之间毫不延迟地更改所有变体?
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()