python时间延迟代码_Python时间延迟

Alright, I want to know how to delay a portion of a program without pausing the entire program.

I'm not necessarily good at python so if you could give me a relatively simple answer if possible, that would be great.

I want to have a turtle draw a circle on screen every time this function is called, this is what I have:

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()

解决方案

You need to put the part of the program you want to delay in its own thread, and then call sleep() in that thread.

I am not sure exactly what you are trying to do in your example, so here is a simple example:

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')

Output:

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.

Notice that we started the thread that will wait 5 seconds first, but it did not block the print_time('now') call, rather it waited in the background.

EDIT:

From J.F. Sebastian's comment, the simpler solution with threading is:

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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值