python - 无法在 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
解决方案
一个问题是您没有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
>
您的输出应该相似但不完全相同。
推荐阅读
- java - 使用自定义 setter 或自定义注解修改 POJO 类字段(在 Spring Boot 中)
- apache-drill - 在读取大量 json 文件并输出到单个文件时,是否有任何设置可以避免在 apache Drill 中使用所有内存?
- r - 将 data.frame 拆分为矩阵并将对角元素相乘以生成新列
- sql - 可以在 Google 表格中进行子选择
- plotly - 使用 Plotly 生成有角度的条形图(来自 Dash 的风险分析)
- arrays - 在文档内的firebase数据库中合并新对象
- html - Next.js 的标签和 HTML 原生的标签一样吗
? - c++ - 如何使用 Visual C++ 构建 wxWidgets
- reactjs - 记忆对象数组的状态
- swift - 使用相同的视图添加和编辑 CoreData 对象