- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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.
# 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()
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.
- Related Articles
- How to move a Tkinter canvas with Mouse?
- How to center an image in canvas Python Tkinter
- How to update an image in a Tkinter Canvas?
- How to insert an image in a Tkinter canvas item?
- How to open PIL Image in Tkinter on Canvas?
- Embedding an Image in a Tkinter Canvas widget using PIL
- How to save HTML Canvas as an Image with canvas.toDataURL()?
- How to draw a png image on a Python tkinter canvas?
- How to add an image in Tkinter?
- How to draw an arc on a tkinter canvas?
- How to resize an image using Tkinter?
- How to clear Tkinter Canvas?
- Tkinter - How to put an outline on a canvas text
- How to save DIV as Image with HTM5 canvas to image with the extension?
- How to reconfigure Tkinter canvas items?