我正在学习 pyqt4 并且正在学习互联网上的教程。不知何故,示例代码中的退出行不起作用:
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
This program creates a quit
button. When we press the button,
the application terminates.
author: Jan Bodnar
website: zetcode.com
last edited: October 2011
"""
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Quit button')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
if __name__ == '__main__':
main()
当我在 gui 中按下 X 按钮或 Quit 按钮时,控制台提示了一些错误:
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "D:\Raymond\Programming Practice\python\gui_qt\lesson1_basic\gui_quit.py", line 46, in <module>
main()
File "D:\Raymond\Programming Practice\python\gui_qt\lesson1_basic\gui_quit.py", line 42, in main
sys.exit(app.exec())
SystemExit: 0
我通过替换行来修复代码
sys.exit(app.exec())
用这条线:
return app.exec()
然后应用程序优雅地退出。但是我不确定这种方法是否有任何缺点,因为它只是返回状态。