如何在 Turtle Graphics 中使用 jpg 文件?

How to use jpg files in Turtle Graphics?

我知道这可能是一个重复的问题,我知道 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 文件???提前致谢!

您可以按如下方式使用Pillow

from PIL import Image
im = Image.open("yourpicture.jpg")
im.rotate(180).show()

经常出现 ,让我们为 turtle 编写一个补丁,以允许 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()