2010-04-18 61 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 ?