完成一个实现网络上传、下载、暂停、取消,能展示下载进度的代码
时间: 2024-01-27 22:05:53 浏览: 25
以下是一个使用Python和tkinter GUI库实现的网络上传、下载、暂停、取消,能够展示下载进度的代码示例。在该示例中,我们使用requests和tqdm库来实现网络请求和进度条的展示。你可以根据自己的需求进行修改和定制。
```python
import requests
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tqdm import tqdm
import threading
class DownloadManager:
def __init__(self, url, filepath):
self.url = url
self.filepath = filepath
self.total_size = 0
self.current_size = 0
self.is_paused = False
self.is_cancelled = False
self.is_downloading = False
def get_total_size(self):
response = requests.head(self.url)
if response.status_code == 200:
content_length = response.headers.get('content-length')
if content_length is not None:
self.total_size = int(content_length)
else:
self.total_size = 0
def download(self):
self.is_downloading = True
response = requests.get(self.url, stream=True)
with open(self.filepath, 'wb') as f:
for chunk in tqdm(response.iter_content(chunk_size=1024), total=self.total_size // 1024, unit='KB', unit_scale=True, desc='Downloading'):
if self.is_paused:
self.is_downloading = False
break
if self.is_cancelled:
self.is_downloading = False
f.close()
self.delete_file()
break
f.write(chunk)
self.current_size += len(chunk)
if not self.is_cancelled:
self.is_downloading = False
messagebox.showinfo('Download Complete', 'File downloaded successfully!')
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
threading.Thread(target=self.download).start()
def cancel(self):
self.is_cancelled = True
def delete_file(self):
try:
os.remove(self.filepath)
except:
pass
class DownloadGUI(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.url_label = tk.Label(self, text='URL:')
self.url_label.grid(row=0, column=0, padx=5, pady=5)
self.url_entry = tk.Entry(self, width=50)
self.url_entry.grid(row=0, column=1, padx=5, pady=5)
self.browse_button = tk.Button(self, text='Browse', command=self.browse_file)
self.browse_button.grid(row=1, column=0, padx=5, pady=5)
self.filepath_entry = tk.Entry(self, width=50)
self.filepath_entry.grid(row=1, column=1, padx=5, pady=5)
self.progress_bar = ttk.Progressbar(self, orient='horizontal', length=300, mode='determinate')
self.progress_bar.grid(row=2, column=1, padx=5, pady=5)
self.download_button = tk.Button(self, text='Download', command=self.download_file)
self.download_button.grid(row=3, column=0, padx=5, pady=5)
self.pause_button = tk.Button(self, text='Pause', command=self.pause_download, state='disabled')
self.pause_button.grid(row=3, column=1, padx=5, pady=5)
self.resume_button = tk.Button(self, text='Resume', command=self.resume_download, state='disabled')
self.resume_button.grid(row=3, column=2, padx=5, pady=5)
self.cancel_button = tk.Button(self, text='Cancel', command=self.cancel_download, state='disabled')
self.cancel_button.grid(row=3, column=3, padx=5, pady=5)
self.pack()
self.download_manager = None
def browse_file(self):
filepath = filedialog.asksaveasfilename(defaultextension='.txt')
self.filepath_entry.delete(0, tk.END)
self.filepath_entry.insert(0, filepath)
def download_file(self):
if self.url_entry.get() == '':
messagebox.showerror('Error', 'URL is required!')
return
if self.filepath_entry.get() == '':
messagebox.showerror('Error', 'File path is required!')
return
self.download_manager = DownloadManager(self.url_entry.get(), self.filepath_entry.get())
self.download_manager.get_total_size()
if self.download_manager.total_size == 0:
messagebox.showerror('Error', 'Failed to get file size!')
return
self.download_button.config(state='disabled')
self.pause_button.config(state='normal')
self.cancel_button.config(state='normal')
threading.Thread(target=self.download_manager.download).start()
self.update_progress()
def pause_download(self):
self.download_manager.pause()
self.pause_button.config(state='disabled')
self.resume_button.config(state='normal')
def resume_download(self):
self.download_manager.resume()
self.resume_button.config(state='disabled')
self.pause_button.config(state='normal')
def cancel_download(self):
self.download_manager.cancel()
self.download_button.config(state='normal')
self.pause_button.config(state='disabled')
self.resume_button.config(state='disabled')
self.cancel_button.config(state='disabled')
def update_progress(self):
if self.download_manager is not None and self.download_manager.is_downloading:
progress = int(self.download_manager.current_size / self.download_manager.total_size * 100)
self.progress_bar['value'] = progress
self.after(100, self.update_progress)
if __name__ == '__main__':
root = tk.Tk()
root.title('Download Manager')
root.geometry('500x200')
DownloadGUI(root)
root.mainloop()
```
这个代码示例实现了一个简单的下载管理器,包括以下功能:
- 输入文件下载地址和保存路径;
- 点击“下载”按钮后,开始下载文件;
- 点击“暂停”按钮后,暂停下载;
- 点击“恢复”按钮后,恢复下载;
- 点击“取消”按钮后,取消下载;
- 实时显示下载进度。