使用python实现简单倒计时exe,供大家参考,具体内容如下

使用tkinter制作界面实现倒计时功能。

  • 使用time.sleep(1)实现 秒级 倒计时
  • 使用线程避免界面卡死
  • 在线程的循环中检测全局标志位,保证计时线程的重置、以及退出
  • 使用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='\nleft 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='\ncountdown: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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。