我很难找到使用PyCharm运行此应用程序时python崩溃的原因。 我将url插入文件(https://download.scdn.co/SpotifySetup.exe)和保存位置(D:\)。只要按下"下载",Python就会停止工作。
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import urllib.request
class Downloader(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
url = QLineEdit()
save_location = QLineEdit()
progress = QProgressBar()
download = QPushButton("Download")
progress.setValue(0)
progress.setAlignment(Qt.AlignHCenter)
url.setPlaceholderText("URL")
save_location.setPlaceholderText("Save folder:")
layout.addWidget(url)
layout.addWidget(save_location)
layout.addWidget(progress)
layout.addWidget(download)
self.setLayout(layout)
self.setWindowTitle("Downloader")
download.clicked.connect(self.download)
def download(self):
url = self.url.text()
save_location = self.save_location.text()
urllib.request.urlretrieve(url, save_location, self.report)
try:
urllib.request.urlretrieve(url, save_location, self.report)
except Exception:
QMessageBox.warning(self, "Warning", "The download failed")
return
QMessageBox.information(self, "Information", "The Download is complete")
self.progress.setValue(0)
self.url.setText("")
self.save_location.setText("")
def report(self, blocknum, blocksize, totalsize):
readsofar = blocknum * blocksize
if totalsize > 0:
percent = readsofar * 100 / totalsize
self.progress.setValue(int(percent))
app = QApplication(sys.argv)
dl = Downloader()
dl.show()
app.exec_()
sys.exit(app.exec_())
答案 0 :(得分:1)
我通过将self
添加到几个变量名来让你的代码在PyCharm中运行。
url -> self.url
save_location -> self.save_location
progress -> self.progress
以下是更新代码的要点: