Open In App
Related Articles

Python Tkinter | Moving objects using Canvas.move() method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level.

Syntax: Canvas.move(canvas_object, x, y)
Parameters: 
canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this
x is horizontal distance from upper-left corner. 
y is vertical distance from upper-left corner.

We will use class to see the working of the move() method.

Class parameters-  

Data members used: 
master 


canvas 
rectangle
Member functions used: 
movement() 
left() 
right() 
up() 
down()
Widgets used: Canvas
Tkinter method used: 
Canvas.create_rectangle() 
pack() 
Canvas.move() 
after() 
bind() 
 

Below is the Python implementation:  

Python3

import tkinter as tk
  
class MoveCanvas(tk.Canvas):
 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
 
        self.dx = 0
        self.dy = 0
  
        self.box = self.create_rectangle(0, 0, 10, 10, fill="black")
 
        self.dt = 25
        self.tick()
      
    def tick(self):
 
        self.move(self.box, self.dx, self.dy)
        self.after(self.dt, self.tick)
 
    def change_heading(self, dx, dy):
        self.dx = dx
        self.dy = dy
  
 
if __name__ == "__main__":
 
    root = tk.Tk()
    root.geometry("300x300")
 
    cvs = MoveCanvas(root)
    cvs.pack(fill="both", expand=True)
 
    ds = 3
  
    root.bind("<KeyPress-Left>", lambda _: cvs.change_heading(-ds, 0))
    root.bind("<KeyPress-Right>", lambda _: cvs.change_heading(ds, 0))
    root.bind("<KeyPress-Up>", lambda _: cvs.change_heading(0, -ds))
    root.bind("<KeyPress-Down>", lambda _: cvs.change_heading(0, ds))
      
    root.mainloop()

                    

Output: 
 


Extra print statements are used in the above code to show the proper working of the move() method. keysym keyword (Tkinter reserved) is used to print which keyboard key is pressed.
 



Last Updated : 02 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads