The Tkinter module comes with the normal Python installation. It allows you to create Python GUI programs for Windows, Linux or Unix on the Mac. In this snippet we put a GIF image (.gif) onto a form's canvas with just a few lines of code. Most of the lines are remarks to explain what is going on.

# Putting a gif image on a canvas with Tkinter
# tested with Python24 by  vegaseat  25jun2005

from Tkinter import *

# create the canvas, size in pixels
canvas = Canvas(width = 300, height = 200, bg = 'yellow')

# pack the canvas into a frame/form
canvas.pack(expand = YES, fill = BOTH)

# load the .gif image file
# put in your own gif file here, may need to add full path
# like 'C:/WINDOWS/Help/Tours/WindowsMediaPlayer/Img/mplogo.gif'
gif1 = PhotoImage(file = 'DrBunsen.gif')

# put gif image on canvas
# pic's upper left corner (NW) on the canvas is at x=50 y=10
canvas.create_image(50, 10, image = gif1, anchor = NW)

# run it ...
13 Years
Discussion Span
Last Post by Ash_4

In case anybody wonders, the Tk root window, the one with the Tk symbol in the corner, is created by default.


To get a GIF picture from the Internet ...

''' Tk_Canvas_Image_url.py
display an image obtained from an internet web page in Tkinter
tested with Python27 and Python34  by  vagaseat   21nov2012

import io
import base64
    # Python2
    import Tkinter as tk
    from urllib2 import urlopen
except ImportError:
    # Python3
    import tkinter as tk
    from urllib.request import urlopen

root = tk.Tk()
root.title("display a website image")
# a little more than width and height of image
w = 520
h = 320
x = 80
y = 100
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# this GIF picture previously downloaded to tinypic.com
image_url = "http://i46.tinypic.com/r9oh0j.gif"

image_byt = urlopen(image_url).read()
image_b64 = base64.encodestring(image_byt)
photo = tk.PhotoImage(data=image_b64)

# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')

# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(10, 10, image=photo, anchor='nw')


Edited by vegaseat: canvas


I'm using this code snippet and i'm trying to get the background to display, but all I get is the grey window. All of my widgets display correctly though. Their code for the widghets is below the canvas code.

 bg_Image = tk.PhotoImage(file = 'Earth.gif')
        canvas = tk.Canvas(master, width = 500, height = 500, bg = '#d3d3d3')
        canvas.create_image(50, 10, image=bg_Image, anchor='nw')

I dont get any error in the shell and the rest of the code runs correctly. These 4 lines just seem to not like me

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.