1

我正在尝试完成我的第一个 Python 学习应用程序,我使用 PyQT5 设计器制作了一个基本的 UI,并使用以下内容进行了测试,但我得到了NameError: global name 'self' is not defined错误。txtProg我的问题是在 GUI 中更新(文本编辑器)的正确程序是什么。

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'main.ui'
#
# Created: Sun Dec  1 20:19:03 2013
#      by: PyQt5 UI code generator 5.1.1
#
# WARNING! All changes made in this file will be lost!

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from mydl import TheDLClass

def progress_hook(txt):
    self.txtProg.setText(txt)


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.txtProg = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.txtProg.setGeometry(QtCore.QRect(50, 80, 661, 431))
        self.txtProg.setObjectName("txtProg")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        self.launchit(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)




    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "My Downloader"))

    def launchit(self, MainWindow):
        MainWindow.setWindowTitle('Launching..')
        with TheDLClass() as dl:
            dl.fd.add_progress_hook(progress_hook)
            dl.download(['http://myurl.com/'])

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
4

1 回答 1

0

self如果不明确传递它,您将无法访问。(使用方法或 lambda)

更优选地,定义progress_hook为实例方法:

def progress_hook(self, txt):
    self.txtProg.setText(txt)

并将其绑定如下:

def launchit(self, MainWindow):
    MainWindow.setWindowTitle('Launching..')
    with TheDLClass() as dl:
        dl.fd.add_progress_hook(self.progress_hook) # <----
        dl.download(['http://myurl.com/'])
于 2013-12-04T14:23:19.440 回答