TKinter Images

You can attach images to the canvas with

welcomeGif = PhotoImage(file = './images/welcome.gif')
canvas.create_image(canvas_width/2,canvas_height/2, image=welcomeGif)

Where the example image is located in a image subfolder of the program with type gif. If you wanted to change the image to another type during the execution of the program you would need to use a slightly different initial call which creates a reference to the image.

welcomeGif = PhotoImage(file = './images/welcome.gif')
background = canvas.create_image(canvas_width/2,canvas_height/2, image=welcomeGif)

This can then be updated during the execution of the program with the canvas.itemconfig command.

gameGif = PhotoImage(file = './images/hellArena.gif')
canvas.itemconfig(background, image = gameGif)

The reality of this as a background image that changes during the game with levels is slightly different. We have to create an array of background images at the start:

backgroundGifs = [PhotoImage(file = './images/welcome.gif')]
backgroundGifs.append(PhotoImage(file = './images/hellArena.gif'))
background = canvas.create_image(canvas_width/2,canvas_height/2, image=backgroundGifs[0])

Which are then available in all methods within the game allowing them to be changed by key events:

canvas.itemconfig(background, image = backgroundGifs[1])

OTHER COMMANDS

Deleting – You can remove an image from the canvas with canvas.delete(name) where name is the name you give it at the point of creation e.g. using the example above it would be background.

Leave a Reply

Your email address will not be published. Required fields are marked *

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