PyQT5应用程序中的自我范围?

时间:2013-12-04 14:20:29

标签: python python-3.x pyqt pyqt5

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

# -*- 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_())

1 个答案:

答案 0 :(得分: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/'])