I need some help for an assignment, I asked a question related to it this evening, but I recognize it was very poorly stated and written. I’ll try to be a little more specific this time.
I have the following piece of code, it’s inside a Game class (that inherits from the Canvas class):
def move_ball(self):
if self.balldir==0:
self.move(self.ball,0,-10)
elif self.balldir==1:
self.move(self.ball,0,10)
root.after(20,self.move_ball)
This method is supossed to move a ball on the canvas, according to self.balldir. If it’s 0, it moves up, if it’s 1, it moves down.
It works just fine for a few seconds, but then it just makes the game slower and slower until it completely stops. I’ve tried with time.sleep as well, but It doesn’t work well with Tkinter (as you probably already know).
I think the problems resides in the use of root.after() , but I really don’t know any other way to move an object for an indefinite amount of time.
Twenty milliseconds seems like a short schedule time which might tweak some platform dependency that I don’t know of. It is also not clear from your code snippet what values
balldirmay be assigned. If you expectballdirto only ever be 0 or 1 you might find this helpful:In your code snippet, if balldir is not in [0, 1] the ball will stop moving and give you no indication of why. To program defensively, especially when beginning never leave an else-less if:
Where the ValueError will keep your program from silently breaking.