1 import sys
2 from PyQt5.QtWidgets import QApplication, QWidget,QToolTip,QPushButton,QMessageBox,QDesktopWidget
3 from PyQt5.QtGui import QIcon,QFont
4 from PyQt5.QtCore import QCoreApplication
5
6 #demo_5:重新关闭按钮x关闭事件,给个提示框提示
7 class Exception(QWidget):
8 def __init__(self):
9 super().__init__()
10 self.initUI()
11
12 def initUI(self):
13 self.setWindowTitle('添加关闭按钮')
14 self.setFont(QFont('微软雅黑',20))
15 self.resize(400,300)
16 self.setWindowIcon(QIcon('1.png'))
17
18 #居中窗口
19 qr = self.frameGeometry()
20 cp = QDesktopWidget().availableGeometry().center()
21 qr.moveCenter(cp)
22 self.move(qr.topLeft())
23
24 self.show()
25
26 def closeEvent(self, QCloseEvent):
27 res=QMessageBox.question(self,'消息','是否关闭这个窗口?',QMessageBox.Yes|QMessageBox.No,QMessageBox.No) #两个按钮是否, 默认No则关闭这个提示框
28 if res==QMessageBox.Yes:
29 QCloseEvent.accept()
30 else:
31 QCloseEvent.ignore()
32
33
34
35 if __name__=='__main__':
36 pp=QApplication(sys.argv)
37 example=Exception()
38 #example.show()
39 sys.exit(pp.exec())
![]()