Python:基本倒数计时器 &函数()>整数() [英] Python : Basic countdown timer & function() > int()

查看:23
本文介绍了Python:基本倒数计时器 &函数()>整数()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个在我的代码后台运行的计时器函数,并使其可以使用/检查时间.我所说的使用/检查是什么意思,我正在尝试这样做,以便我可以调用该计时器函数并将其用作整数.

I'm trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I'm trying to make it so I can call upon that timer function and use it as integer.

这是我目前拥有的代码:

This is the code I currently have:

def timer():
    for endtime in range(0, 15):
        print(15 - endtime)
        time.sleep(1)

def hall():
    timer()
    while (timer > 0):
       do something

目前仅使用 print(15 - endtime) 来确认它正在倒计时.

Currently only using print(15 - endtime) for confirmation it is counting down.

但是代码现在所做的是执行倒计时,仅此而已,它永远不会触及 while 循环.当然,最后一个问题是我无法将函数设置为 int.因此,我正在寻找某种方法来检查计时器的位置并在该 while 循环中使用它.

But what the code does now is execute the countdown and that's it, it never touches the while loop. And of course the last issue is I can't set a function to an int. So I'm looking for some way where I can check where the timer is at and use it in that while loop.

推荐答案

如果你这样做,你将不得不使用多线程.

The way you do it, you'll going to have to use multithread.

这是另一种更简单的方法:在脚本开始时,使用 time.time() 设置一个 time_start 变量,其中包含自纪元以来的秒数然后当你需要经过的秒数时,使用 time.time() - time_start :

Here is another, simpler approach : On your script beginning, set a time_start variable with the number of seconds since the epoch using time.time() Then when you need the number of elapsed seconds, use time.time() - time_start :

t_start = time.time()
# do whatever you'd like
t_current = int(time.time()-t_start) # this way you get the number of seconds elapsed since start.

您也可以将其放入函数中,将 t_start 定义为全局变量.

You can put that in a function as well, defining t_start as a global variable.

import time
t_start = time.time()

def timer():
    global t_start
    print(str(int(time.time()-t_start)))


print('start')
time.sleep(2)
timer()
time.sleep(3)
timer()

这篇关于Python:基本倒数计时器 &函数()>整数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆