我刚开始尝试构建简单的 GUI,因为我一直使用命令行脚本并想探索更多。我正在使用 PyQt4 和 Python 3 的最新版本。
问题是给定下面的代码,单击第一个窗口中的按钮时,第二个窗口不会显示,但我不明白为什么。我错过了什么?该脚本功能齐全(当然,第二个窗口部分除外),因此只需复制/粘贴即可尝试。
import sys
from PyQt4 import QtCore, QtGui
class GreetWindow(QtGui.QMainWindow):
def __init__(self):
# main init
QtGui.QMainWindow.__init__(self)
self.setWindowTitle('File Checker!')
self.centralWidget = QtGui.QWidget()
self.tLabel = QtGui.QLabel('Hello, and welcome! Please, close me!', self.centralWidget)
self.bClose = QtGui.QPushButton('Close', self.centralWidget)
# layout
self.lVBox = QtGui.QVBoxLayout()
self.lVBox.setSpacing(2)
self.lVBox.addWidget(self.tLabel)
self.lVBox.addWidget(self.bClose)
# signal connections
self.connect(self.bClose, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('close()'))
self.connect(self.bClose, QtCore.SIGNAL('clicked()'), self.showSecond)
# layout combination
self.centralWidget.setLayout(self.lVBox)
self.setCentralWidget(self.centralWidget)
def showSecond():
self.theSecond = SecondWindow()
self.theSecond.show()
class SecondWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle('This is the second!')
self.centralWidget = QtGui.QLabel('Mission accomplished')
self.setCentralWidget(self.centralWidget)
def main():
app = QtGui.QApplication(sys.argv)
ex = GreetWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
顺便说一句,我真的很感谢批评这个简单脚本的编码方式。我现在从 GUI 开始,我想以最 Pythonic 的方式开始。谢谢大家!