2015-01-12 39 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)