我尝试为 turtle 制作函数,使其非常容易绘制形状。代码如下所示:
import turtle as t
def square():
tw = t.Screen()
for i in range(4):
t.forward(100)
t.right(90)
tw.exitonclick()
def triangle():
tw = t.Screen()
for i in range(3):
t.forward(100)
t.right(120)
tw.exitonclick()
def star():
tw = t.Screen()
for i in range(5):
t.forward(150)
t.right(144)
tw.exitonclick()
当我在 shell 中运行此代码时,会发生终结者错误:
>>> square()
>>> triangle()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
triangle()
File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 11, in triangle
t.forward(100)
File "<string>", line 5, in forward
turtle.Terminator
>>> star()
>>> square()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
square()
File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 5, in square
t.forward(100)
File "<string>", line 5, in forward
turtle.Terminator
>>>
我不明白问题是什么,因为我什至使用了 exitonclick()
。
最佳答案
您的 turtle 程序结构不正确。你不需要这样做:
tw = t.Screen()
...
tw.exitonclick()
在每个函数中。 Screen()
只需需要调用一次; exitonclick()
应该只被调用一次。尝试这种重组:
import turtle as t
def square():
for i in range(4):
t.forward(100)
t.right(90)
def triangle():
for i in range(3):
t.forward(100)
t.right(120)
def star():
for i in range(5):
t.forward(150)
t.right(144)
t.penup()
t.goto(150, 150)
t.pendown()
square()
t.penup()
t.goto(-150, 150)
t.pendown()
triangle()
t.penup()
t.goto(150, -150)
t.pendown()
star()
screen = t.Screen()
screen.exitonclick()
如果您想以交互方式执行代码,那也可以。只需删除函数定义后的所有内容,以交互方式将其加载到 Python 中并执行以下操作:
>>> star()
或者任何你想运行的东西。您不需要调用 Screen()
并且 exitonclick()
在交互工作时没有意义。
关于Python Turtle.Terminator 即使在使用 exitonclick() 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534458/