Python时间延迟

时间:2015-01-12 03:36:54

标签: python time delay turtle-graphics

好吧,我想知道如何在不暂停整个程序的情况下延迟程序的一部分。 我不一定擅长python,所以如果你可以给我一个相对简单的答案,那就太好了。

我希望每次调用此函数时都会在屏幕上画一个圆圈,这就是我所拥有的:

import time
from random import randint
turtle5 = turtle.Turtle()    

coinx = randint(-200, 200)
coiny = randint(-200, 200)

turtle5.pu()
turtle5.goto(coinx, coiny)
turtle5.pd()
turtle5.begin_fill()
turtle5.fillcolor("Gold")
turtle5.circle(5, 360, 8)
turtle5.end_fill()
time.sleep(1)
turtle5.clear()

2 个答案:

答案 0 :(得分:1)

您需要将要延迟的程序部分放在自己的线程中,然后在该线程中调用sleep()。

我不确定你在你的例子中想要做什么,所以这里有一个简单的例子:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

class Wait(threading.Thread):
    def __init__(self, seconds):
        super(Wait, self).__init__()
        self.seconds = seconds
    def run(self):
        time.sleep(self.seconds)
        print_time('after waiting %d seconds' % self.seconds)

if __name__ == '__main__':
    wait_thread = Wait(5)
    wait_thread.start()
    print_time('now')

输出:

The time now is: Mon Jan 12 01:57:59 2015.
The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015.

请注意,我们启动的线程将先等待5秒,但它不会阻止print_time(现在')调用,而是在后台等待。

修改

来自J.F. Sebastian的评论,更简单的线程解决方案是:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

if __name__ == '__main__':
    t = threading.Timer(5, print_time, args = ['after 5 seconds'])
    t.start()
    print_time('now')

答案 1 :(得分:1)

turtle.ontimer()调用具有指定延迟的函数:

turtle.ontimer(your_function, delay_in_milliseconds)