PyQt5 - 处理点击事件时pythonw.exe崩溃

时间:2016-07-16 16:41:40

标签: python python-3.x pyqt pyqt5

我是PyQt5的新手,我有一个错误(pythonw.exe不再工作),代码如下:

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication

class Example(QWidget):

def __init__(self):
    super().__init__()
    self.initUI()

def initUI(self):               

    qbtn = QPushButton('Quit', self)
    qbtn.clicked.connect(self.q)
    qbtn.resize(qbtn.sizeHint())
    qbtn.move(50, 50)       

    self.setGeometry(300, 300, 250, 150)
    self.setWindowTitle('Quit button')    
    self.show()

def q():
    print('test')
    sys.exit()

if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() app.exec_()

首先它起作用,但直到我按下“退出”按钮。然后弹出错误消息。 如果我将q()函数放在类之外(并将“self.q”更改为“q”),它可以正常工作。 有什么问题?

提前致谢。

Windows 7 Python 3.4.3(x86) PyQt 5.5.1(x86)

1 个答案:

答案 0 :(得分:1)

那是因为当q()在类中时,它需要一个强制参数作为第一个参数,这通常称为self,并且在调用方法时由python隐式传递给你( q()不是q(self))。就像你在类中使用initUI方法一样,当你把它放在类之外时,它只是一个普通的函数,而不是一个方法(类中的函数),所以定义函数是好的没有self

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):               
        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(self.q)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)       

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button')    
        self.show()

    def q(self):
        print('test')
        sys.exit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    app.exec_()