用30行python代碼設計一個屬于自己的計算器
今天來看一下如何來使用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_() 本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!