【问题标题】:How to use jpg files in Turtle Graphics?如何在 Turtle Graphics 中使用 jpg 文件?
【发布时间】:2019-06-14 12:22:56
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x turtle-graphics


    【解决方案1】:

    经常出现,让我们为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()
    

    【讨论】:

    • 非常感谢,这真的有效。感谢您花时间帮助我!
    【解决方案2】:

    您可以使用Pillow,如下:

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

    【讨论】:

      猜你喜欢
      • 2016-07-04
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2011-09-08
      • 2018-06-14
      • 2012-10-31
      相关资源
      最近更新 更多