- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
# 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()
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.
- How to Move an Image in Tkinter canvas with Arrow Keys?
- How to draw a line following mouse coordinates with tkinter?
- Zoom HTML5 Canvas to Mouse Cursor
- How to clear Tkinter Canvas?
- How to add text inside a Tkinter Canvas?
- How to make a Tkinter canvas rectangle transparent?
- How to reconfigure Tkinter canvas items?
- How to create a Button on a Tkinter Canvas?
- How to draw a line on a Tkinter canvas?
- How to correctly select multiple items with the mouse in Tkinter Treeview?
- How to update an image in a Tkinter Canvas?
- How to delete lines from a Python tkinter canvas?
- How to draw an arc on a tkinter canvas?
- Mouse Position in Python Tkinter
- How to draw a dashed line on a Tkinter canvas?