Python using Turtle to show images

I’ve been puzzling how to use images in a Python script since yesterdays “Scissor, Paper, Stone” game. I don’t like “Googling” for an answer straight away when I’m working on personal projects and instead bounced through a few ideas before I clicked that turtle could be used to display an image using a few lines of code:

———

import turtle

file_img=r’image.gif’

screen=turtle.Screen()

screen.bgpic(file_img)

———

The above example shows the picture as the background, which in my current line of thinking would allow another image to be used as the turtle (e.g. have one image as a background and another as a sprite that user could move).

Some issues I ran into getting this to work:

1) The image needed to be a GIF (Graphics Interchange Format), if it is not a GIF file then Python 3 throws up some errors:

  File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py”, line 1481, in bgpic

    self._bgpics[picname] = self._image(picname)

  File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py”, line 479, in _image

    return TK.PhotoImage(file=filename)

  File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py”, line 3539, in __init__

    Image.__init__(self, ‘photo’, name, cnf, master, **kw)

  File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py”, line 3495, in __init__

    self.tk.call((‘image’, ‘create’, imgtype, name,) + options)

_tkinter.TclError: couldn’t recognize data in image file “image.png”

2) The default image viewing software (Preview) on Mac OS X does not by default show the option to export images to GIF format. To export to GIF, click “File”, “Export…” and then hold the left “option alt” key on the keyboard as you click the “Format” drop down, GIF is then available.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.