-->

Method for having animated movement for canvas obj

2019-01-20 13:21发布

问题:

I have been trying to learn how move canvas items from google, however the method shown most places doesnt seem to work for me as intended. right now i am just trying to get a ball move from one side of the screen to the other over the period of 1 second

from tkinter import *

root = Tk()
c = Canvas(root, width = 200, height = 100)
c.pack()
ball = c.create_oval(0, 25, 50, 75)
for i in range(25):
    c.move(ball, 6, 0)
    root.after(40)
root.mainloop()

when run, this seems to move the ball before opening the window, however if i call upon mainloop first, the window opens but the ball doesn't move.

Unsure of how it is meant to be set out but if anyone knows that would be awesome.

回答1:

The basic idea is to use after to create an animation loop. In it's simplest form it looks like this:

def animate():
    c.move(ball, 6, 0)
    root.after(33, animate)

This will move the object 6 pixels, and the cause itself to run again in 33 milliseconds. Changing that number (33 in this example) determines how fast the item moves. 33ms is roughly 30fps.

Of course, you'll want to add a check to see if the item is off screen so you can stop the loop or move the item back to the left edge. Also, you shouldn't rely on global variables, but I wanted to remove as much extra code as possible so you can see the fundamental nature of the function.

Here is a complete working example based off of the code in the question:

from tkinter import *

def animate():
    c.move(ball, 6, 0)
    root.after(33, animate)

root = Tk()
c = Canvas(root, width = 200, height = 100)
c.pack()
ball = c.create_oval(0, 25, 50, 75)
animate()
root.mainloop()