我知道这可能是一个重复的问题,而且我知道Turtle模块仅支持gif文件,但是我真的想在Turtle中使用jpg或png。我阅读了turtle.py的源代码,并尝试从
修改行885和1132。if name.lower().endswith(".gif"):
到
if data.lower().endswith(".gif") or data.lower().endswith(".jpg"):
然后我保存了文件,但是即使现在尝试
screen.addshape("fireball.jpg")
它给我一个错误:
File "C:\Users\PC\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 1135, in register_shape
raise TurtleGraphicsError("Bad arguments for register_shape.\n"
turtle.TurtleGraphicsError: Bad arguments for register_shape.
使用jpg文件该怎么办???预先谢谢您!
答案 0 :(得分:2)
经常出现 ,让我们为乌龟写一个补丁,以允许PIL.ImageTk.PhotoImage()
可以处理的所有事情:
patch_turtle_image.py
from turtle import TurtleScreenBase
from PIL import ImageTk
@staticmethod
def _image(filename):
return ImageTk.PhotoImage(file=filename)
TurtleScreenBase._image = _image
# If all you care about is screen.bgpic(), you can ignore what follows.
from turtle import Shape, TurtleScreen, TurtleGraphicsError
from os.path import isfile
# Methods shouldn't do `if name.lower().endswith(".gif")` but simply pass
# file name along and let it break during image conversion if not supported.
def register_shape(self, name, shape=None): # call addshape() instead for original behavior
if shape is None:
shape = Shape("image", self._image(name))
elif isinstance(shape, tuple):
shape = Shape("polygon", shape)
self._shapes[name] = shape
TurtleScreen.register_shape = register_shape
def __init__(self, type_, data=None):
self._type = type_
if type_ == "polygon":
if isinstance(data, list):
data = tuple(data)
elif type_ == "image":
if isinstance(data, str):
if isfile(data):
data = TurtleScreen._image(data) # redefinition of data type
elif type_ == "compound":
data = []
else:
raise TurtleGraphicsError("There is no shape type %s" % type_)
self._data = data
Shape.__init__ = __init__
测试程序:
from turtle import Screen, Turtle
import patch_turtle_image
screen = Screen()
screen.bgpic('MyBackground.jpg')
screen.register_shape('MyCursor.png')
turtle = Turtle('MyCursor.png')
turtle.forward(100)
screen.exitonclick()
答案 1 :(得分:0)
您可以按以下方式使用Pillow:
from PIL import Image
im = Image.open("yourpicture.jpg")
im.rotate(180).show()