FTP 下载,带有显示当前下载状态的文本标签

2023-12-02

我制作了一个 GUI,点击后“下载”按钮程序将从 FTP 服务器下载文件。这样做时,我希望标签更新,例如:“正在连接……” -> “正在下载……” -> “已下载!”我尝试使用线程模块执行此操作,但似乎不起作用:

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...


以下代码应该执行以下操作:

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 进度

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

FTP 下载,带有显示当前下载状态的文本标签 的相关文章

随机推荐