Python Rapid GUI Programming 第二篇。 30行寫一個更奇葩的計算器。Python 基礎教程


接上一篇GUI編程的日志,現在我們來寫一個正常點程序。先讓我們看一下程序的樣子。

image

看似正常多了。我們有了一個框框,一個X。而且不需要命令行輸入了!

根據上一篇日志所述,我們需要載入模塊。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM