#!/usr/bin/python3# -*- coding: utf-8 -*-"""
Py40 PyQt5 tutorial
This program creates a menubar. The
menubar has one menu with an exit action.
author: Jan Bodnar
website: py40.com
last edited: January 2015
"""import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
classExample(QMainWindow):def__init__(self):super().__init__()
self.initUI()definitUI(self):
exitAction = QAction(QIcon('exit.png'),'&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
self.statusBar()#创建一个菜单栏
menubar = self.menuBar()#添加菜单
fileMenu = menubar.addMenu('&File')#添加事件
fileMenu.addAction(exitAction)
self.setGeometry(300,300,300,200)
self.setWindowTitle('Menubar')
self.show()if __name__ =='__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
#!/usr/bin/python3# -*- coding: utf-8 -*-"""
Py40 PyQt5 tutorial
This program creates a toolbar.
The toolbar has one action, which
terminates the application, if triggered.
author: Jan Bodnar
website: py40.com
last edited: January 2015
"""import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
classExample(QMainWindow):def__init__(self):super().__init__()
self.initUI()definitUI(self):
exitAction = QAction(QIcon('exit24.png'),'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
self.setGeometry(300,300,300,200)
self.setWindowTitle('Toolbar')
self.show()if __name__ =='__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
上面的例子,创建了一个简单的工具栏。工具栏有一个按钮,点击关闭窗口。
结合在一起
这个例子中,有菜单条,工具栏和状态栏的小窗口
#!/usr/bin/python3# -*- coding: utf-8 -*-"""
Py40 PyQt5 tutorial
This program creates a skeleton of
a classic GUI application with a menubar,
toolbar, statusbar, and a central widget.
author: Jan Bodnar
website: py40.com
last edited: January 2015
"""import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication
from PyQt5.QtGui import QIcon
classExample(QMainWindow):def__init__(self):super().__init__()
self.initUI()definitUI(self):
textEdit = QTextEdit()
self.setCentralWidget(textEdit)
exitAction = QAction(QIcon('exit24.png'),'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.close)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
toolbar = self.addToolBar('Exit')
toolbar.addAction(exitAction)
self.setGeometry(300,300,350,250)
self.setWindowTitle('Main window')
self.show()if __name__ =='__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())