Moving balls in Tkinter Canvas

Tkinter is a standard Python library which is used to create GUI-based applications. To create a simple moving ball application, we can use the Canvas widget which allows the user to add images, draw shapes, and animating objects. The application has the following components,

  • A Canvas widget to draw the oval or ball in the window.

  • To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom).

  • To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration.

  • Finally, execute the code to run the application.


# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window

# Set the size of the window

# Make the window size fixed

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)

# Create an oval or ball in the canvas widget
ball=canvas.create_oval(10,10,50,50, fill="green3")

# Move the ball

def move_ball():
   global xspeed, yspeed

   canvas.move(ball, xspeed, yspeed)
   (leftpos, toppos, rightpos, bottompos)=canvas.coords(ball)
   if leftpos <=0 or rightpos>=700:

   if toppos <=0 or bottompos >=350:


canvas.after(30, move_ball)



Running the above code will display an application window that will have a movable ball in the canvas.