如图所示,当点击quit按钮时,退出窗口
代码:
1 """ 2 This program creates a quit 3 button. When we press the button, 4 the application terminates. 5 """ 6 7 import sys 8 from PyQt5.QtWidgets import QWidget, QPushButton, QApplication 9 10 11 class Example(QWidget): 12 13 def __init__(self): 14 super().__init__() 15 16 self.initUI() 17 18 def initUI(self): 19 20 # create a push button 21 quitbtn = QPushButton('Quit', self) 22 # QPushButton(string text, QWidget parent = None) 23 # The text parameter is a text that will be displayed on the button 24 # The parent is a widget on which we place our button 25 26 quitbtn.clicked.connect(QApplication.instance().quit) 27 # The clicked signal is connected to the quit() method which terminates the application. 28 # The communication is done between two objects: the sender and the receiver. 29 # The sender is the push button, the receiver is the application object. 30 31 quitbtn.resize(quitbtn.sizeHint()) 32 quitbtn.move(50, 50) 33 34 self.setGeometry(300, 300, 250, 150) 35 self.setWindowTitle('Quit button') 36 self.show() 37 38 39 if __name__ == '__main__': 40 41 app = QApplication(sys.argv) 42 ex = Example() 43 sys.exit(app.exec_())