PyQt5 - pythonw.exe 处理点击事件时崩溃
PyQt5 - pythonw.exe crash on handling clicked event
我是 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()
</p>
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
app.exec_()
首先它起作用,但直到我按下 "quit" 按钮。然后弹出错误信息。
如果我将 q() 函数放在 class 之外(并将 "self.q" 更改为 "q"),它可以正常工作。
有什么问题吗?
提前致谢。
Windows 7
Python 3.4.3 (x86)
PyQt 5.5.1 (x86)
那是因为当 q()
在 class 内部时,它需要一个强制参数作为第一个参数,这通常称为 self
并由 [=19 隐式传递给你=] 当您调用该方法时(q()
而不是 q(self)
)。就像你在 class 中使用 initUI
方法一样,当你将它放在 class 之外时,它只是一个普通函数而不是一个方法(函数在 class), 所以定义函数不用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_()
我是 PyQt5 的新手,我遇到了一个错误(pythonw.exe 不再工作),代码如下:
import sys from PyQt5.QtWidgets import QWidget, QPushButton, QApplication from PyQt5.QtCore import QCoreApplicationclass 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()
</p> if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() app.exec_()
首先它起作用,但直到我按下 "quit" 按钮。然后弹出错误信息。 如果我将 q() 函数放在 class 之外(并将 "self.q" 更改为 "q"),它可以正常工作。 有什么问题吗?
提前致谢。
Windows 7 Python 3.4.3 (x86) PyQt 5.5.1 (x86)
那是因为当 q()
在 class 内部时,它需要一个强制参数作为第一个参数,这通常称为 self
并由 [=19 隐式传递给你=] 当您调用该方法时(q()
而不是 q(self)
)。就像你在 class 中使用 initUI
方法一样,当你将它放在 class 之外时,它只是一个普通函数而不是一个方法(函数在 class), 所以定义函数不用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_()