pyQt: eg3
2017-02-13 16:31 一方书斋 阅读(217) 评论(0) 编辑 收藏 举报import sys import urllib2 from PyQt4 import QtCore from PyQt4 import QtGui class Form(QtGui.QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) date = self.getdata() rates = sorted(self.rates.keys()) dateLabel = QtGui.QLabel(date) self.fromComboBox = QtGui.QComboBox() self.fromComboBox.addItems(rates) self.fromSpinBox = QtGui.QDoubleSpinBox() self.fromSpinBox.setRange(0.01, 10000000.00) self.fromSpinBox.setValue(1.00) self.toComboBox = QtGui.QComboBox() self.toComboBox.addItems(rates) self.toLabel = QtGui.QLabel("1.00") grid = QtGui.QGridLayout() grid.addWidget(dateLabel, 0, 0) grid.addWidget(self.fromComboBox, 1, 0) grid.addWidget(self.fromSpinBox, 1, 1) grid.addWidget(self.toComboBox, 2, 0) grid.addWidget(self.toLabel, 2, 1) self.setLayout(grid) self.connect(self.fromComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.updateUi) self.connect(self.toComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.updateUi) self.connect(self.fromSpinBox, QtCore.SIGNAL("valueChanged(double)"), self.updateUi) self.setWindowTitle("Currency") def updateUi(self): to = unicode(self.toComboBox.currentText()) from_ = unicode(self.fromComboBox.currentText()) amount = ((self.rates[from_] / self.rates[to]) * self.fromSpinBox.value()) self.toLabel.setText("{0:.2f}".format(amount)) def getdata(self): # Idea taken from the Python Cookbook self.rates = {} try: date = "Unknown" fh = urllib2.urlopen("http://www.bankofcanada.ca" "/en/markets/csv/exchange_eng.csv") for line in fh: line = line.rstrip() if not line or line.startswith(("#", "Closing ")): continue fields = line.split(",") if line.startswith("Date "): date = fields[-1] else: try: value = float(fields[-1]) self.rates[unicode(fields[0])] = value except ValueError: pass return "Exchange Rates Date: " + date except Exception, e: return "Failed to download:\n{0}".format(e) app = QtGui.QApplication(sys.argv) form = Form() form.show() app.exec_()