首页 > 解决方案 > 无法在 Python turtle 模块中添加形状 - 没有此类文件或目录错误

问题描述

我正在尝试将海龟的形状更改为 8 位链接图像。我有我想要保存到与我的源代码相同的目录的图像(你可以看到它os.getcwd()。)我想知道为什么我会收到这个错误以及如何修复它。谢谢!

from turtle import Turtle, Screen
import os

print(os.getcwd())


wn = Screen()
wn.bgcolor('lightblue')

spaceship = Turtle()
spaceship.color('red')
newshape = Screen().addshape('8bitlink.png.gif')
spaceship.shape(newshape)
spaceship.penup()

错误如下所示:

Traceback (most recent call last):
  File "/Users/colind/Desktop/Spaceship Game.py", line 12, in <module>
    newshape = Screen().addshape('8bitlink.png.gif')
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 1133, in register_shape
    shape = Shape("image", self._image(name))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 479, in _image
    return TK.PhotoImage(file=filename)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3542, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3498, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "8bitlink.png.gif": no such file or directory

标签: pythonturtle-graphics

解决方案


一个问题是您没有addshape()正确调用:

newshape = Screen().addshape('8bitlink.png.gif')
spaceship.shape(newshape)

由于addshape()不返回任何内容,它会在文件名下注册图像形状,因此您应该改为执行以下操作:

from turtle import Turtle, Screen

wn = Screen()
wn.bgcolor('lightblue')

wn.addshape('8bitlink.png.gif')

spaceship = Turtle()
spaceship.shape('8bitlink.png.gif')
spaceship.color('red')
spaceship.penup()

# ...

wn.mainloop()

当我以“8bitlink.png.gif”的名称存储 GIF 图像时,这对我有用。file您可以通过运行 Unix命令来说服自己和我们,您拥有一个实际的 GIF 图像:

> file 8bitlink.png.gif
8bitlink.png.gif: GIF image data, version 89a, 24 x 24
>

您的输出应该相似但不完全相同。


推荐阅读