2015-01-12 38 views
1

好的,我想知道如何在不暂停整个程序的情况下延迟程序的一部分。 我不一定擅长python,所以如果你可以给我一个相对简单的答案,如果可能的话,那会很好。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() 
+1

哪功能?您发布的代码中没有功能。 –

+0

'好的',你必须更具体。 – GLHF

+1

你说你想“在不暂停整个程序的情况下延迟一部分程序”。好的,那么你的程序在延迟时间内会做什么,什么时候它不是*画乌龟? –

回答

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('now')调用,而是等待在后台。

编辑:

从JF 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

这里你不需要一个自定义的线程子类。有'threading.Timer'。你可以避免在GUI中创建线程(比如'turtle'),网络代码。参见[在python中推迟函数](http://stackoverflow.com/a/14040516/4279) – jfs

1

turtle.ontimer()调用与指定的延时功能:

turtle.ontimer(your_function, delay_in_milliseconds)