用python 30行設計一個屬於自己的計算器

pythontab發表於2013-02-18

今天來看一下如何來使用python設計一個屬於自己的計算器,哈哈,python的gui還是蠻強的哦~~下面開始吧

先上截圖哈

image

先載入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_()

相關文章