2010-04-18 63 views
4

我目前正在研究python中的精灵工作表工具,它将组织导出到一个xml文档中,但我遇到了一些尝试动画预览的问题。我不太确定如何使用python来计算帧频。例如,假设我拥有所有适当的帧数据和绘图功能,我将如何编码时间以每秒30帧(或任何其他任意速率)显示。Python动画计时

回答

8

做到这一点最简单的方法是用Pygame

import pygame 
pygame.init() 

clock = pygame.time.Clock() 
# or whatever loop you're using for the animation 
while True: 
    # draw animation 
    # pause so that the animation runs at 30 fps 
    clock.tick(30) 

做第二个最简单的方法是手动:

import time 

FPS = 30 
last_time = time.time() 
# whatever the loop is... 
while True: 
    # draw animation 
    # pause so that the animation runs at 30 fps 
    new_time = time.time() 
    # see how many milliseconds we have to sleep for 
    # then divide by 1000.0 since time.sleep() uses seconds 
    sleep_time = ((1000.0/FPS) - (new_time - last_time))/1000.0 
    if sleep_time > 0: 
     time.sleep(sleep_time) 
    last_time = new_time 
+0

谢谢你,非常有帮助。我是Python的新手,但努力工作以更熟悉它。 – eriknelson 2010-04-18 03:21:57

0

还有就是threading模块中的Timer类。这可能比使用time.sleep用于某些目的更方便。

>>> from threading import Timer 
>>> def hello(who): 
... print 'hello %s' % who 
... 
>>> t = Timer(5.0, hello, args=('world',)) 
>>> t.start()  # and five seconds later... 
hello world 
0

您可以使用select?它通常用于等待I/O完成,但看看签名:

select.select(rlist, wlist, xlist[, timeout]) 

是这样,你可以这样做:

timeout = 30.0 
while true: 
    if select.select([], [], [], timeout): 
     #timout reached 
     # maybe you should recalculate your timeout ?