Turtle模块在while循环中使用计数器时崩溃


from turtle import *
import tkinter
r = 0
shapes = [shape("square"), shape("turtle"), shape("triangle")]
def hello():
while True:
right(100)
forward(100)
left(100)
r +=1


hello()
tkinter.mainloop()

每当我删除r +=1它工作得很好。但我一加进去,它就崩溃了。我想要使用计数器的主要原因是因为最初我的代码是这样的:

from turtle import *
import tkinter
r = 0
shapes = [shape("square"), shape("turtle"), shape("triangle")]
def hello():
while True:
right(r)
forward(r)
left(r)
r +=1


hello()
tkinter.mainloop()

但是这会使程序崩溃得更快,很有趣。有人有类似的问题吗?

您的程序有几个问题,除了r没有被声明为global。首先,它是一个无限循环,所以你的计数器永远不会被检查。其次,它进口了不必要的东西。让我们重新编写代码,使它不再永远循环,而是在海龟走出窗口时返回counter的值:

from turtle import *
def hello():
counter = 0
width, height = window_width(), window_height()
while -width/2 < xcor() < width/2 and -height/2 < ycor() < height/2:
right(counter)
forward(counter)
left(counter)
counter += 1
return counter
print(hello())
mainloop()

> python3 test.py
31
>

最新更新