Tkinter Canvas Basic Animation
The method used for animation design is move( ), and the format used is as follows.
canvas.move(ID, xMove, yMove) # ID is an object number
canvas.update() # Forced repainting on canvas
xMove,yMove are the distance in pixels along x and y axis respectively.
Example#1
The moving ball is designed to move 5 pixels at a time.
from tkinter import *
import time
tk = Tk()
tk.title("apidemos.com")
canvas = Canvas(tk,width=500, height=150) # Create canvas
canvas.pack()
canvas.create_oval(10,50,60,100,fill="yellow",outline='lightgray')
for x in range(0,80):
canvas.move(1,5,0) # ID=1 x-axis shifted by 5 pixels, y-axis unchanged
tk.update() # Forced tkinter redraw
time.sleep(0.05)
# tk.mainloop()
Output:
The above program is executed using a loop, and line 13 is equivalent to defining a move every 0.05s. In fact, we can move in any direction by setting the parameters of the move() method.
Example#2
Expand the canvas height to 300 pixels, moving the x-axis by 5 pixels and the y-axis by 2 pixels each time.
from tkinter import *
import time
tk = Tk()
tk.title("apidemos.com")
canvas = Canvas(tk,width=500, height=300) # Create Canvas
canvas.pack()
canvas.create_oval(10,50,60,100,fill="yellow",outline='lightgray')
for x in range(0,80):
canvas.move(1,5,2) # ID=1 Shift 5 pixels on the x-axis and 2 pixels on the y-axis
tk.update() # Forced tkinter redraw
time.sleep(0.05)
# tk.mainloop()
Output: