使用 Turtle 后如何关闭 window

How can I close a window after using Turtle

我正在尝试在 Spyder 和 Jupyter 中使用 Turtle,但是当我尝试关闭 window 时遇到了问题。

我在 Spyder 3.3.1 和 Jupyter 5.6.0 上使用 Python 3.7,在 Windows 10

这是我试过的

import turtle as trtl

trtl.forward(100)
trtl.left(90)
trtl.forward(100)
trtl.left(90)
trtl.forward(100)
trtl.left(90)
trtl.forward(100)
trtl.exitonclick()

我工作正常,但是如果我关闭 window 并再次尝试 运行 相同的代码,我会收到以下错误:

---------------------------------------------------------------------------
Terminator                                Traceback (most recent call last)
<ipython-input-9-ad2d84897daf> in <module>()
      1 import turtle as trtl
      2 
----> 3 trtl.forward(100)
      4 trtl.left(90)
      5 trtl.forward(100)

~\Anaconda3\lib\turtle.py in forward(distance)

Terminator: 

我尝试了 done()bye()exitonclick() 的多种组合,但我无法实现

这里摘自海龟documentation:

If the value “using_IDLE” in the configuration dictionary is False (default value), also enter mainloop. Remark: If IDLE with the -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE’s own mainloop is active also for the client script.

因此,您可以将using_IDLE = True添加到turtle.cfg文件来解决这个问题。这将阻止 exitonclick() 进入主循环。

有点晚了,但我认为在 Jupyter 中解决这个问题的最佳选择是:

import importlib
import turtle
importlib.reload(turtle)

turtle.forward(1)
turtle.exitonclick()

问题是 TK 应用程序是在 import turtle 中创建的,当您在 window 中单击 bye 时终止。之后当您尝试执行一些 turtle 指令时,TK 应用程序终止,然后发生错误。于是重新加载turtle包解决问题