无法在Python turtle模块中添加形状-没有此类文件或目录错误

时间:2018-07-26 19:28:43

标签: python turtle-graphics

我正在尝试将乌龟的形状更改为8bit链接图像。我有要与我的源代码保存在同一目录中的图像(您可以使用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

1 个答案:

答案 0 :(得分:0)

一个问题是您没有正确调用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图像时,这对我有用。您可以通过运行Unix file命令来使自己和我们相信您拥有一个真实的GIF图像:

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

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