依据某文件路径下是否存在A文件(举例),B文件(举例),在交互界面上实现进度条功能,总体实现效果为,当文件路径下出现A文件,进度条为10%,又出现B文件,进度条为20%。
实现代码如下:
import os
import tkinter as tk
# 定义每个文件的进度百分比
file_progress = {'1.txt': 0.1, '2.txt': 0.1,'3.txt': 0.1,'4.txt': 0.7}
class ProgressBar:
def __init__(self, master):
self.master = master
self.master.title("进度条")
# 创建进度条和标签
self.progressbar = tk.Canvas(master, width=300, height=30, bg='white')
self.progressbar.pack(pady=10)
self.label = tk.Label(master, text="Rate of progress:0%")
self.label.pack()
# 创建一个定时器,用于定期更新进度条
self.step = 0
self.timer()
def timer(self):
if self.step >= 100:
self.label.config(text='Complete')
return
# 计算当前的进度百分比并更新进度条和标签
progress = calculate_progress()
self.step = int(progress * 100)
self.progressbar.delete("all")
self.progressbar.create_rectangle(0, 0, 300 * progress, 30, fill="blue")
self.label.config(text=f'Rate of progress:{self.step}%')
# 定时器每隔一段时间更新一次进度条
self.master.after(100, self.timer)
def calculate_progress():
path = r"***" # 在指定目录下及其子目录下查找
progress = 0
for root, dirs, files in os.walk(path):
for file in files:
if file in file_progress:
progress += file_progress[file]
return progress
if __name__ == '__main__':
root = tk.Tk()
pb = ProgressBar(root)
root.mainloop()