Efficient way to move an object in Tkinter Canvas
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 balldir
may be assigned. If you expect balldir
to only ever be 0 or 1 you might find this helpful:
def move_ball(self):
assert 0 <= self.balldir <= 1
self.move(self.ball, 0, 10 * (-1 * self.balldir))
root.after(...
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:
if name == "dhcarmona":
pass
elif name == "msw":
pass
else
raise ValueError, "name is not as expected"
Where the ValueError will keep your program from silently breaking.
精彩评论