Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

tkinter - Method for having animated movement for canvas objects python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...