Method for having animated movement for canvas objects python

回眸只為那壹抹淺笑 提交于 2019-11-28 14:05:47

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!