首页 > 解决方案 > MainWindow 上的 TypError (self, str)

问题描述

我对 Pyqt5 很陌生,并试图制作一个导入/导出 UI。有几个错误,找不到我做错了什么..如果我能得到一些答案,我会很高兴..

我想我用init和 super 做了一些错误的事情,但无法弄清楚。

这是我的代码和错误。

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        MainWindow.setWindowTitle("Gen")
        MainWindow.setFixedSize(1250,802)

#Box 1
        self.groupBox = QtWidgets.QGroupBox(MainWindow)
        self.groupBox.setGeometry(5,0, 350,400)
        self.groupBox.setTitle("BOX 1")

#Box 2
        self.groupBox_2 = QtWidgets.QGroupBox(MainWindow)
        self.groupBox_2.setGeometry(5,400,350,400)
        self.groupBox_2.setTitle("BOX 2")

#Import and Export Button at Box 2
        self.But_Import = QtWidgets.QPushButton(self.groupBox_2)
        self.But_Import.setGeometry(5,360,169,30)
        self.But_Import.setText("Import")

        self.But_Export = QtWidgets.QPushButton(self.groupBox_2)
        self.But_Export.setGeometry(176,360,169,30 )
        self.But_Export.setText("Export")

#class ImageLabel(QtWidgets.QLabel):



if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    Window = MainWindow()
    Window.show()
    sys.exit(app.exec_())


和错误

Traceback (most recent call last):
  File "D:/NAME/Desktop/fiel/Gen_v1.0.0.2.py", line 47, in <module>
    Window = MainWindow()
  File "D:/NAME/Desktop/fiel/Gen_v1.0.0.2.py", line 17, in __init__
    MainWindow.setWindowTitle("Gen")
TypeError: setWindowTitle(self, str): first argument of unbound method must have type 'QWidget'

标签: pythonpyqt5

解决方案


我想你以某种方式继承了pyuic生成代码的作用,我强烈建议你避免模仿它们的行为。

正如评论中已经建议的那样,您应该修改后的前两行super()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Gen")
        self.setFixedSize(1250,802)

这是为什么?

两种方法都是实例方法,所有实例方法都需要第一个参数是类的实例。

实例方法期望实例引用作为第一个参数(通常称为self)。当直接从实例调用方法时,实例参数 ( self) 被隐式设置。

想象一下:

class MyClass(object):
    def someMethod(self, argument=None):
        print('self is "{}", argument is "{}"'.format(self, argument))

然后运行以下命令:

>>> MyClass.someMethod('hello')
self is "hello", argument is "None"

>>> instance = MyClass()
>>> instance.someMethod('hello')
self is "<__main__.MyClass object at 0xb5c27dec>", argument is "hello"

如您所见,第一次尝试显示这self是您给出的字符串参数,而第二次正确显示这self是 MyClass 的一个实例并且参数是“hello”。这正是您的情况所发生的情况:使用类而不是实例调用函数使您的第一个字符串参数成为实例参数。

(一个非常简单的)关于方法类型的注释:PyQt 是一个绑定,并且作为 python 和实际 Qt C++ 对象之间的一种层。在这种情况下,类方法有时在类被实例化之前是“未绑定方法”,而实例方法则成为“绑定方法”。正确的解释其实要复杂一些,不过这里不是讨论这个的地方。


推荐阅读