<p>试试看:</p>
<pre><code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MainWindow(QMainWindow):
windowList = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('Main interface')
self.showMaximized()
# Create Menu Bar
self.createMenus()
def createMenus(self):
# Create login action
self.printAction1 = QAction(self.tr("Entrance"), self)
self.printAction1.triggered.connect(self.on_printAction1_triggered)
# Create exit action
self.printAction2 = QAction(self.tr("Exit"), self)
self.printAction2.triggered.connect(self.on_printAction2_triggered)
# Create menu, add actions
self.printMenu = self.menuBar().addMenu(self.tr("Entrance and Exit"))
self.printMenu.addAction(self.printAction1)
self.printMenu.addAction(self.printAction2)
# Step 1: Login
def on_printAction1_triggered(self):
self.close()
dialog = LoginDialog()
if dialog.exec_()==QDialog.Accepted:
the_window = MainWindow()
self.windowList.append(the_window) # ! It is important !
the_window.show()
def on_printAction2_triggered(self):
self.close()
# Interface close event
def closeEvent(self, event):
print("The End")
class LoginDialog(QDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('Login interface')
self.resize(250, 200)
self.setFixedSize(self.width(), self.height())
self.setWindowFlags(Qt.WindowCloseButtonHint)
# Configure UI controls
self.frame = QFrame(self)
self.frame.resize(250, 200)
self.verticalLayout = QVBoxLayout(self.frame)
self.lineEdit_account = QLineEdit()
self.lineEdit_account.setPlaceholderText("Please enter nickName (admin)")
self.verticalLayout.addWidget(self.lineEdit_account)
self.lineEdit_password = QLineEdit()
self.lineEdit_password.setPlaceholderText("Please enter your password (admin)")
self.verticalLayout.addWidget(self.lineEdit_password)
self.pushButton_enter = QPushButton()
self.pushButton_enter.setText("OK")
self.verticalLayout.addWidget(self.pushButton_enter)
self.pushButton_quit = QPushButton()
self.pushButton_quit.setText("Cancel")
self.verticalLayout.addWidget(self.pushButton_quit)
# bindings button Event
self.pushButton_enter.clicked.connect(self.on_pushButton_enter_clicked)
self.pushButton_quit.clicked.connect(QCoreApplication.instance().quit)
def on_pushButton_enter_clicked(self):
# Check nickName
if self.lineEdit_account.text() != "admin":
return
# Check password
if self.lineEdit_password.text() != "admin":
return
# Close the dialog and return 1 when checking
self.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
dialog = LoginDialog()
if dialog.exec_()==QDialog.Accepted:
the_window = MainWindow()
the_window.show()
sys.exit(app.exec_())
</code></pre>
<p><a href="https://i.stack.imgur.com/oCSBP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oCSBP.png" alt="enter image description here"/></a></p>