Method for having animated movement for canvas objects python

我的梦境 提交于 2019-11-27 08:07:14

问题


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()


来源:https://stackoverflow.com/questions/32454935/method-for-having-animated-movement-for-canvas-objects-python

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