Skip to content Skip to sidebar Skip to footer

Tkinter Moving Balls Program Creating 4 Balls Instead Of 2

I have created a program that made a ball move around a canvas and bounce of the edge of the canvas. This worked very well so I tried to add another ball but instead of creating 2

Solution 1:

The problem is that you changed the class Ball in addition to adding a second ball. The idea of object oriented programming (i.e. in simple words classes in python) is to create a class, here Ball, that defines how ONE generic ball works. You can from this class create as many objects (here ball1, ball2, etc.) as you want.

In your code you just have to

  1. remove the line

    self.ball2 = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red")

  2. remove the complete move_ball2 function

  3. Change

ball2.move_ball2(x0,y0)

to

ball2.move_ball(x0,y0)

and it will work as expected.

Solution 2:

You are initializing two balls in your __init()__ method.

self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red")
self.ball2 = canvas.create_oval(self.x1, self.y1, self.x2, self.y2,fill="red")

When the object is created for the class two balls instead of one. So changing the init method in the class should fix it. You need to create two different objects for two different balls, rather than two different variables in the class itself.

classBall:

    #creates ballsdef__init__(self, canvas, x1,y1,x2,y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.canvas = canvas
        self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red")

Also, you have two different methods for moving balls 1 and 2. One method should work for both balls.

ball1 = Ball(canvas, 10, 10, 30, 30)
ball2 = Ball(canvas, 60, 60, 80, 80)

When the two statements are executed they return objects of the class Ball to the variables ball1 and ball2. These objects are independent of each other and the move_ball method would be called on them individually without affecting each other. Creating two functions for two different variables defeats the purpose of creating a class.

You might want to read a little more on classes and objects from here and here. There are video tutorials on classes and objects and how they're implemented on tkinter.

Post a Comment for "Tkinter Moving Balls Program Creating 4 Balls Instead Of 2"