Moving an Image with tkinter and canvas

Moving an image

In another article we’ve seen how to make a rectangle move on the screen, a bit like in a 2d game. Now we will see how to make an image to move. It’s even easier thann the previous example. Let’s assume we got this image

and we want it to move up and down in our canvas.

The result is the one showed here:

What kind of code we need?

The code to move the sprite

We need:

  • to create a PhotoImage object to load the image
    img = tk.PhotoImage(file="mega.png")
  • the create_image method to draw it on the canvas

    image = canvas.create_image(10, 10, anchor=tk.NW, image=img)
  • the bind method to make the movement happen when we press a certain key
    root.bind("<Key>", move)
    
  • the move method to move the image on the canvas
    canvas.move(image, -10, 0)

     

So, it si pretty easy, thanks to the move method.

The whole code

We will learn how to load an image with PhotoImage, how to insert it in the canvas with create_image.

We will also use bind and the method move.

# move an Image on the canvas with tkinter
 
import tkinter as tk
 
# Create the window with the Tk class
root = tk.Tk()
 
# Create the canvas and make it visible with pack()
canvas = tk.Canvas(root, width=800, height=800)
canvas.pack() # this makes it visible
 
# Loads and create image (put the image in the folder)
img = tk.PhotoImage(file="mega.png")
image = canvas.create_image(10, 10, anchor=tk.NW, image=img)
 
 
def move(event):
    """Move the sprite image with a d w and s when click them"""
    if event.char == "a":
        canvas.move(image, -10, 0)
    elif event.char == "d":
        canvas.move(image, 10, 0)
    elif event.char == "w":
        canvas.move(image, 0, -10)
    elif event.char == "s":
        canvas.move(image, 0, 10)
 
# This bind window to keys so that move is called when you press a key
root.bind("<Key>", move)
 
# this creates the loop that makes the window stay 'active'
root.mainloop()

Compare this code with the same thing in pygame (aka: moving a sprite on a window with pygame)

This time we will use the pygame libraries to move the sprite. These libraries are made jus for games, as you can guess by the name, so it should be faster and smoother than the ouput of the code made with tkinter in theory.

import pygame
from pygame.locals import *

pygame.init()
clock = pygame.time.Clock()
size = 400, 300
screen = pygame.display.set_mode(size,0,32)
pygame.display.set_caption('GAME')
x, y = 200, 130

sprite=pygame.image.load('mega.gif')
loop = True
while loop:
    screen.blit(sprite,(x,y))
    for event in pygame.event.get():
        if event.type==QUIT:
            loop = False
            #sys.exit()
    
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        x -= 2
    if keys[pygame.K_RIGHT]:
        x += 2
    if keys[pygame.K_UP]:
        y -= 2
    if keys[pygame.K_DOWN]:
        y += 2
    
    pygame.display.flip()
    clock.tick(120)

pygame.quit()

See here the result with pygame

This is the one with tkinter

Moving a rectangle on the canvas

In this example you can see how you can move a rectangle on the canvas, instead of an image. The code is very similar to the one above, but with some differences. You choose wich is the better for your needs of readability or other purposes your code must have for you.

import tkinter as tk

root = tk.Tk()
WIDTH = HEIGHT = 400
x1 = y1 = WIDTH / 2
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)

left, right, up, down = -10,10,-10,10

def keypress(event):
    global text
    x = 0
    y = 0
    if event.char == "a": x = left 
    elif event.char == "d": x = right
    elif event.char == "w": y = up
    elif event.char == "s": y = down    
    canvas.move(c1, x, y)


root.bind("<Key>", keypress)
root.mainloop()

Watch it working on repl.it

 

Moving a rectangle with a text inside with tkinter

Take a look at this post I made recently (november 2019), where I add to this code some text, so that you can move a text inside the rectangle.

You can go here to read the text.

Other posts about the tkinter module

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.