pyqt5制作一个压缩包下载器
时间: 2024-02-05 17:04:52 浏览: 79
通过PYQT5设计的打包软件
好的,以下是一个简单的PyQt5压缩包下载器的示例代码:
```python
import os
import sys
import urllib.request
import zipfile
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QMessageBox, QProgressBar, QFileDialog
class Downloader(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置窗口标题和大小
self.setWindowTitle('压缩包下载器')
self.resize(400, 200)
# 创建标签、行编辑框、按钮和进度条控件
self.url_label = QLabel('下载链接:', self)
self.url_label.move(20, 20)
self.url_edit = QLineEdit(self)
self.url_edit.move(100, 20)
self.url_edit.resize(280, 20)
self.save_label = QLabel('保存路径:', self)
self.save_label.move(20, 50)
self.save_edit = QLineEdit(self)
self.save_edit.move(100, 50)
self.save_edit.resize(200, 20)
self.select_button = QPushButton('选择', self)
self.select_button.move(310, 50)
self.select_button.clicked.connect(self.select_folder)
self.download_button = QPushButton('下载', self)
self.download_button.move(20, 90)
self.download_button.clicked.connect(self.download)
self.progress_bar = QProgressBar(self)
self.progress_bar.move(20, 130)
self.progress_bar.resize(360, 20)
self.show()
def select_folder(self):
# 弹出文件对话框,让用户选择保存路径
folder_path = QFileDialog.getExistingDirectory(self, '选择保存路径')
if folder_path:
self.save_edit.setText(folder_path)
def download(self):
url = self.url_edit.text()
save_path = self.save_edit.text()
if not url or not save_path:
QMessageBox.warning(self, '警告', '下载链接或保存路径不能为空!')
return
# 显示进度条控件
self.progress_bar.setValue(0)
self.progress_bar.show()
# 下载文件并显示进度
with urllib.request.urlopen(url) as response, open(os.path.join(save_path, os.path.basename(url)), 'wb') as out_file:
data = response.read()
total_size = len(data)
block_size = 8192
written_size = 0
while True:
buffer = response.read(block_size)
if not buffer:
break
written_size += len(buffer)
out_file.write(buffer)
progress = int(written_size / total_size * 100)
self.progress_bar.setValue(progress)
QApplication.processEvents()
# 如果下载的是zip文件,解压缩并删除zip文件
if url.endswith('.zip'):
with zipfile.ZipFile(os.path.join(save_path, os.path.basename(url)), 'r') as zip_file:
zip_file.extractall(save_path)
os.remove(os.path.join(save_path, os.path.basename(url)))
QMessageBox.information(self, '提示', '下载完成!')
if __name__ == '__main__':
app = QApplication(sys.argv)
downloader = Downloader()
sys.exit(app.exec_())
```
这个程序界面比较简单,只有一个输入框和一个按钮。用户可以在输入框中输入要下载的文件的URL,然后点击按钮开始下载。当下载进度发生变化时,程序会自动更新进度条控件。如果下载的是zip文件,程序会自动解压缩并删除zip文件。
阅读全文