6行Python代码实现进度条效果(Progress、tqdm、alive-progress和PySimpleGUI库)
在项目开发过程中加载、启动、下载项目难免会用到进度条,如何使用Python实现进度条呢?
这里为小伙伴们分享四种Python实现进度条的库:Progress库、tqdm库、alive-progress库和PySimpleGUI库,其中前三个是文本进度条库,最后一个是可以在GUI上运行的进度条。
1、Progress库
Progress是一种文本进度条库,库详细说明参加GitHub。
使用库之前需要进行安装,pip指令如下所示:
pipinstallprogressbar2
实现总耗时1S的进度条,代码如下所示:
importtime importprogressbar p=progressbar.ProgressBar() N=10 #加上进度,就是将range(N)放到ProgressBar()中 foriinp(range(N)): #每次延时0.1S time.sleep(0.1)
效果如下所示:
还可以设置为中文提示,代码如下所示:
importtime importprogressbar defcustom_len(value): #Thesecharacterstakeupmorespace characters={ '进':2, '度':2, } total=0 forcinvalue: total+=characters.get(c,1) returntotal bar=progressbar.ProgressBar( widgets=[ '进度:', progressbar.Bar(), '', progressbar.Counter(format='%(value)02d/%(max_value)d'), ], len_func=custom_len, ) foriinbar(range(10)): time.sleep(0.1)
效果如下所示:
2、tqdm库
tqdm库消耗资源很低,每次迭代大约60ns(gui=True时为80ns),并且已针对性能下降进行了单元测试。完善的ProgressBar具有800ns/iter的开销,库详细说明参加GitHub。
使用库之前需要进行安装,pip指令如下所示:
pipinstalltqdm
实现总耗时1S的进度条,代码如下所示:
importtime fromtqdmimporttqdm fromtqdm._tqdmimporttrange N=10 foriintqdm(range(N)): time.sleep(0.1)
效果如下所示:
不仅如此,tqdm库在实现进度条的同时还可以遍历迭代的对象,做到高效率工作,例如遍历列表["a","b","c","d"]的同时实现进度条,代码如下所示:
fromtqdmimporttqdm importtime text="" forcharintqdm(["a","b","c","d"]): time.sleep(0.1) text=text+char print(text)
效果如下所示:
3、alive-progress库
alive-progress库是一种具有动态效果的智能进度条,库详细说明参加GitHub。
使用库之前需要进行安装,pip指令如下所示:
pipinstallalive-progress
实现总耗时10S的动态效果进度条,代码如下所示:
fromalive_progressimportalive_bar importtime items=range(10)#retrieveyoursetofitems withalive_bar(len(items))asbar:#declareyourexpectedtotal foriteminitems:#iterateasusual #processeachitem bar()#callafterconsumingoneitem time.sleep(1)
效果如下所示:
4、PySimpleGUI库
PySimpleGUI库是基于Tkinter、Remi、wxPython和PyQt库GUI库,我们可以基于它实现在GUI中添加进度条,当然这只是抛砖引玉,小伙伴们可以使用自己喜爱的GUI库实现进度条设计,库详细说明参加GitHub。
使用库之前需要进行安装,pip指令如下所示:
pipinstallpysimplegui
实现总耗时10S的动态GUI效果进度条,代码如下所示:
importPySimpleGUIassg importtime items=range(10) fori,iteminenumerate(items): sg.one_line_progress_meter('ProgressMeter',i+1,len(items),'-key-') time.sleep(1)
效果如下所示:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。