How to move a Tkinter canvas with Mouse?


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 move images in a particular direction on the Canvas widget using the move() method.

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

We can follow these steps to allow our image to move 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 mouse buttons 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('logo.png'))
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)

# Define a function to allow the image to move within the canvas
def move(e):
   global image
   image = ImageTk.PhotoImage(Image.open('logo.png'))
   img = canvas.create_image(e.x, e.y, image=image)

# Bind the move function
canvas.bind("<B1-Motion>", move)

win.mainloop()

Output

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

Now, click on the Canvas and drag the object around with your mouse.

Updated on: 18-Jun-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements