本篇内容介绍了“python中如何实现简单倒计时功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
具体内容如下:
使用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='
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()
“python中如何实现简单倒计时功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。