使画布对象具有动画运动的方法python [英] Method for having animated movement for canvas objects python

查看:62
本文介绍了使画布对象具有动画运动的方法python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习如何从 google 移动画布项目,但是在大多数地方显示的方法似乎对我不起作用.现在我只是想让球在 1 秒内从屏幕的一侧移动到另一侧

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

运行时,这似乎在打开窗口之前移动了球,但是如果我首先调用 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.

推荐答案

基本思想是使用 after 来创建动画循环.最简单的形式如下:

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)

这会将对象移动 6 个像素,并且原因本身会在 33 毫秒内再次运行.更改该数字(在本例中为 33)决定了项目移动的速度.33ms 大约是 30fps.

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

这篇关于使画布对象具有动画运动的方法python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆