App下載

在python中怎么實(shí)現(xiàn)簡單倒計(jì)時(shí)功能?簡單倒計(jì)時(shí)實(shí)現(xiàn)方法!

深巷的貓 2021-08-20 13:41:13 瀏覽數(shù) (4283)
反饋

在之前小編寫個(gè)在html5中怎么實(shí)現(xiàn)倒計(jì)時(shí)效果的文章,今天我們就來說說“在python中怎么實(shí)現(xiàn)簡單倒計(jì)時(shí)功能?”這個(gè)問題,并和大家分享有關(guān)于解決方法的思路和方法!

具體內(nèi)容如下:

使用tkinter制作界面實(shí)現(xiàn)倒計(jì)時(shí)功能。

  • 使用time.sleep(1)實(shí)現(xiàn) 秒級 倒計(jì)時(shí)
  • 使用線程避免界面卡死
  • 在線程的循環(huán)中檢測全局標(biāo)志位,保證計(jì)時(shí)線程的重置、以及退出
  • 使用pyinstaller -F file.py -w 生成exe文件,-w表示隱藏控制臺,-F表示生成單文件

代碼如下:

#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/4/19 14:09
# @Author  : dongdong
# @File    : CountdownGUI.py
# @Software: PyCharm

from tkinter import *
import time
import threading
def cyclethread():
    global counttime
    global restartflag
    global runflag
    restartflag=False

    if (timestr.get().isdigit()):
        counttime = int(timestr.get()) * 60
    else:
        runflag=False
        return;
    while (1):
        if(restartflag):
            counttime = int(timestr.get()) * 60
            restartflag=False
        if(exitflag):
            sys.exit()

        counttime=counttime-1
        v='
left time:'+str(counttime//60)+' :'+str(counttime%60)
        textshow.set(v)
        root.update()
        if (counttime <= 0):
            runflag = False
            return
        time.sleep(1)

def startCount():
    global  restartflag
    global runflag
    restartflag=True
    if( not runflag):
        th=threading.Thread(target=cyclethread)
        th.setDaemon(True)
        th.start()
        runflag = True

def exitfun():
    global exitflag
    exitflag=True
    sys.exit()

restartflag=False
exitflag=False
counttime=None
runflag=False
root=Tk()
root.geometry('250x120')
root.title('TimeCounter')

timestr = StringVar(value="30")
textshow=StringVar(value='
CountDown:30min ')

text0=Label(root,text='Input time(min):').grid(row=0,column=0,columnspan=3)
entext=Entry(root,textvariable=timestr).grid(row=0,column=3,columnspan=1)

# bnframe=ttk.Frame(root).grid(row=1,column=0,columnspan=4)
stbn=Button(root,text='Start',command=startCount).grid(row=1,column=2,columnspan=1)
enbn=Button(root,text='Exit',command=exitfun).grid(row=1,column=3,columnspan=1)

text=Label(root,textvariable=textshow).grid(row=2,column=0,columnspan=4)
root.mainloop()

那么以上就是有關(guān)于“在python中怎么實(shí)現(xiàn)簡單倒計(jì)時(shí)功能?”這個(gè)問題的相關(guān)內(nèi)容和解決方法思路分享!更多有關(guān)于python的相關(guān)內(nèi)容我們都可以在W3Cschool進(jìn)行學(xué)習(xí)和了解。

0 人點(diǎn)贊