我曾尝试为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()
发布于 2018-06-07 00:47:28
我在做一个学校项目的时候也犯了同样的错误。在对turtle库进行了一些研究之后,我发现了一个名为TurtleScreen._RUNNING的变量,如果该变量设置为True,则会打开turtle窗口,否则会出现turtle.Terminator错误。每次您关闭turtle屏幕时,TurtleScreen._RUNNING会自动设置为True,如果您想避免这种情况,您可以简单地编写这行代码TurtleScreen._RUNNING = True (当然,您需要在此之前导入turtle )。
发布于 2017-08-07 03:27:58
您的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()在交互工作时没有意义。
发布于 2017-08-09 08:47:18
让screen.exitonclick()方法成为代码中的最后一条语句,而不缩进它。
在使用Python IDE (如Pycharm、Spyder等)时,可以使用此方法。
我不知道您是否听说过screen.mainloop()方法
此方法使您能够在Python IDE中运行代码时看到代码的输出。
如果没有此方法,您的输出将出现在flash中。
我重写了你的代码,这是我的
from turtle import Turtle
t=Turtle()
def square():
t.up()
t.setpos(-50,-50)
t.down()
for i in range(4):
t.forward(100)
t.right(90)
def triangle():
t.up()
t.setpos(50,50)
t.down()
for i in range(3):
t.forward(100)
t.right(120)
def star():
t.up()
t.setpos(-200,100)
t.down()
for i in range(5):
t.forward(150)
t.right(144)
square()
triangle()
star()
t.screen.exitonclick()下面是输出的output of my program
您还可以查看这个优秀的guide in Python turtle
https://stackoverflow.com/questions/45534458
复制相似问题