How to Move an Image in Tkinter canvas with Arrow Keys?


Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can provide a dynamic attribute to the image defined in a Canvas widget by using the move() method.

Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the Image in the Canvas. We declare images globally in order to track the Image location in the Canvas.

We can follow these steps to make our image movable within the canvas,

  • First, define the Canvas widget and add images to it.

  • Define the move() function to allow the image to be dynamic within the Canvas.

  • Bind the Arrow Keys with the function that allows images to be moved within the Canvas.

Example

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)

# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('favicon.ico'))
img = canvas.create_image(250, 120, anchor=NW, image=image)

def left(e):
   x = -20
   y = 0
   canvas.move(img, x, y)

def right(e):
   x = 20
   y = 0
   canvas.move(img, x, y)

def up(e):
   x = 0
   y = -20
   canvas.move(img, x, y)

def down(e):
   x = 0
   y = 20
   canvas.move(img, x, y)

# Bind the move function
win.bind("<Left>", left)
win.bind("<Right>", right)
win.bind("<Up>", up)
win.bind("<Down>", down)

win.mainloop()

Output

Running the above code will display a window that contains an image that can be moved across the window using the arrow keys.

You can move the object on the canvas around with the Arrow keys.

Updated on: 18-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements