gpt4 book ai didi

python - 每次在 Python 中按下同一个按钮时,如何按顺序更改 turtle 图像?

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:55 25 4
gpt4 key购买 nike

我想编写一个程序,在每次按下“n”键时按顺序更改 turtle 图像。

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

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

关于python - 每次在 Python 中按下同一个按钮时,如何按顺序更改 turtle 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com