FTP download with text label showing the current status of the download(带有显示当前下载状态的文本标签的 FTP 下载)
问题描述
我制作了一个 GUI,点击 下载" 按钮后,程序将从 FTP 服务器下载文件.这样做时,我希望标签更新,例如:"Connecting..." ->正在下载..." ->已下载!"我试过用线程模块做,但它似乎不起作用:
I made a GUI in which after I click "Download" button the program will download files from FTP server. When doing that I want the label to update e.g: "Connecting..." -> "Downloading..." -> "Downloaded!" I tried doing it with threading module but it seems to not work:
def updater(self):
self.updateStatusText.setText("Status: Connecting...")
thread = threading.Thread(target=self.download)
thread.start()
while thread.isAlive():
self.updateStatusText.setText("Status: Still Downloading...")
def download(self):
ftp = FTP('testdomain.com')
ftp.login(user='username', passwd='password')
ftp.cwd('/main_directory/')
filename = 'testfile.bin'
with open(filename, 'wb') as localfile:
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
ftp.quit()
localfile.close()
它只是下载文件,根本不改变文本标签.我必须在这里使用 QThread 吗?我也尝试使用 asyncio,但等待 self.updateStatusText.setText("Connecting...")
似乎返回 None 并且我得到 TypeError...
It just downloads the file and doesn't change the text label at all. Do I have to use QThread here? I also tried using asyncio but awaiting self.updateStatusText.setText("Connecting...")
seems to return None and I get TypeError...
推荐答案
下面的代码应该这样做:
The following code should do:
class DownloadThread(QtCore.QThread):
data_downloaded = QtCore.pyqtSignal(object)
def run(self):
self.data_downloaded.emit('Connecting...')
ftp = FTP('example.com')
ftp.login(user='user', passwd='password')
ftp.cwd('/main_directory/')
self.data_downloaded.emit('Downloading...')
filename = 'testfile.bin'
with open(filename, 'wb') as localfile:
ftp.retrbinary('RETR ' + filename, localfile.write)
ftp.quit()
self.data_downloaded.emit('Done')
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.label = QtGui.QLabel
self.button = QtGui.QPushButton("Start")
self.button.clicked.connect(self.start_download)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button)
layout.addWidget(self.label)
self.setLayout(layout)
def start_download(self):
self.thread = DownloadThread()
self.thread.data_downloaded.connect(self.on_data_ready)
self.thread.start()
def on_data_ready(self, data):
self.label.setText(unicode(data))
基于:在多线程 PyQT 中更新 GUI 元素.
您的后续问题:从另一个运行 FTP 下载的线程更新 PyQt 进度
这篇关于带有显示当前下载状态的文本标签的 FTP 下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有显示当前下载状态的文本标签的 FTP 下载
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01