用python 30行设计一个属于自己的计算器,python30行,from __fut
用python 30行设计一个属于自己的计算器,python30行,from __fut
今天来看一下如何来使用python设计一个属于自己的计算器,哈哈,python的gui还是蛮强的哦~~下面开始吧
先上截图哈
先载入QT4所用的模块以及计算所用的math模块。
from __future__ import division #精确除法 import sys from math import * from PyQt4.QtCore import * from PyQt4.QtGui import *
根据截图,这个应用程序用了两个widgets ,一个是QTextBrowser这是一个只读的文本或者HTML查看器, 另一个是QLineEdit 是一个单行的可写的文本查看器。
根据QT的规则,所有的字符都为Uni编码。
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.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi) self.setWindowTitle("Calculate coding by Kaysin")
这样就完成了初始画面的定义。
QVBoxLayout() 就是一个可以放置widget的页面。
而下面的addWidget方法,就是将所创建的widget添加进新的页面。
下面有触发信号,按下回车。
载入函数 upadteUi
def updateUi(self): try: text = unicode(self.lineedit.text()) self.browser.append("%s = <b>%s</b>" % (text, eval(text))) except: self.browser.append( "<font color=red>%s is invalid!</font>" % text)
这个很好理解,就是判断输入是否合法,出现异常则输出不合法。
我们看下源程序。
from __future__ import division import sys from math import * from PyQt4.QtCore import * from PyQt4.QtGui 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.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi) self.setWindowTitle("Calculate coding by Kaysin") def updateUi(self): try: text = unicode(self.lineedit.text()) 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_()
相关内容
- Python GUI 教程 25行代码写一个小闹钟,python25行,一个小
- python gui - wxPython多线程支持,pythonwxpython,当然,如果你
- Python开发:windows下安装twisted过程,pythontwisted,首先安装
- Python 打包工具 PyInstaller 2.1 发布,pythonpyinstaller,重写了
- 使用Python开发windows桌面程序【超简单】,pythonwindows,二
- Python实现对文件夹内文本文件递归查找,,而有的时候,
- Python使用wxPython、py2exe编写桌面程序,wxpythonpy2exe,使用
- python生成验证码,文字转换为图片,,这些都是动态生成
- 最好的Python机器学习库,python机器,这一点很容易看出,
- 基于 Python 和 Scikit-Learn 的机器学习介绍,pythonscikit-l
评论关闭