首页 文章

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

提问于
浏览
0

我是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 回答

  • 1

    那是因为当 q() 在类中时,它需要一个强制参数作为第一个参数,这通常被称为 self ,当你调用方法时,它会被python隐式传递给你( q() 不是 q(self) ) . 就像你在类中使用了 initUI 方法一样,当你把它放在类之外时,'s just a normal function and not a method again (function in a class), so it'很好地定义了没有 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_()
    

相关问题