遇到问题 运行ning turtle.py,似乎无法将模块正确地安装到 运行

Having issues running turtle.py, can't seem to get the module to run properly

我在这里很新,还在上学,如果这很简单,我深表歉意,但我似乎无法让乌龟在 pycharm 或任何其他 IDE 中工作。如果有人有任何信息,请告诉我。

我的代码:

#Super basic code to test turtle in pycharm
import turtle
wn = turtle.Screen()
yertle = turtle.Turtle()
wn.exitonclick()

yertle.forward(100)
yertle.left(120)
yertle.forward(100)

window 关闭后出错:

Traceback (most recent call last):
  File "C:\Users\Tom\PycharmProjects\pythonProject\main.py", line 6, in <module>
    yertle.forward(100)
  File "C:\Program Files\Python39\lib\turtle.py", line 1638, in forward
    self._go(distance)
  File "C:\Program Files\Python39\lib\turtle.py", line 1606, in _go
    self._goto(ende)
  File "C:\Program Files\Python39\lib\turtle.py", line 3159, in _goto
    screen._pointlist(self.currentLineItem),
  File "C:\Program Files\Python39\lib\turtle.py", line 756, in _pointlist
    cl = self.cv.coords(item)
  File "<string>", line 1, in coords
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 2762, in coords
    self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"

问题是当你调用 turtle.exitonclick() 方法时,它告诉 turtle

Hey, the program is over, time to allow the user to close the window by clicking.

现在,你得到这个错误是因为在 window 关闭之后,还有更多的 turtle 命令让程序通过,这些命令需要一个 turtle window 到 运行上。

修复很简单,将 wn.exitonclick() 调用重新定位到代码底部,您确定程序已结束:

import turtle

wn = turtle.Screen()

yertle = turtle.Turtle()
yertle.forward(100)
yertle.left(120)
yertle.forward(100)

wn.exitonclick()

您需要将 wn.exitonclick() 移至脚本末尾。在 window 关闭之前,调用不会 return,因此当你执行 yertle 的三个命令时为时已晚。