在 ubuntu 系统上 GUI 编程,PyQt5 是个不错的选择。首先,当然是安装 PyQt5 了。终端输入命令: pip3 install PyQt5 即可。
1. 建立一目录 x01.PyQtHello, 进入后添加文件 hello.py 如下:
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * app = QApplication(sys.argv) dlg = QDialog() label = QLabel("<font color=red size=5><b>Hello PyQt5!</b></font>") layout = QVBoxLayout() layout.addWidget(label) dlg.setLayout(layout) dlg.show() app.exec_()
保存后终端输入命令: python3 hello.py 运行即可。效果图如下:
2. 再添加一文件 calc.py 如下:
from __future__ import division import sys from math import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineEdit = QLineEdit("Type an expression and press enter.") self.lineEdit.selectAll() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineEdit) self.setLayout(layout) self.lineEdit.setFocus() self.lineEdit.returnPressed.connect(self.updateUi) self.setWindowTitle("Calculate") def updateUi(self): text = self.lineEdit.text() try: self.browser.append("%s = <b>%s</b>" % (text, eval(text))) except: self.browser.append("<font color=red>%s is invalid!</font>" % text) app = QApplication(sys.argv) form = Form() form.show() app.exec_()
同样,输入命令: Python3 calc.py 运行即可。效果图如下:
通过两个小实验,发现 PyQt5 用来 GUI 编程还是不错的,推荐: http://zetcode.com/gui/pyqt5/