PythonCalulator (GUI example)
Zur Navigation springen
Zur Suche springen
A Calculator
[Bearbeiten]# [Create a window]
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from math import *
class Window(QWidget):
"""Main window handling
"""
def __init__(self, parent = None):
"""Constructor
@param parent: the window parent or <i>none</i>
"""
QWidget.__init__(self, parent)
self.setWindowTitle(self.tr("Calculator"))
self._labelFormula = QLabel(self.tr("Formula:"))
self._editFormula = QLineEdit()
self._editFormula.setToolTip(self.tr("Any mathematical formula like '2.777+sin(3.14/3)+log(1.99e+7)'"))
self._labelResult = QLabel(self.tr("Result:"))
self._labelResult2 = QLabel("")
self._buttonCalc = QPushButton(self.tr("Calc"))
self._buttonCalc.default = True
self._listHistory = QListWidget()
# Put the widgets in a layout (now they start to appear):
layout = QGridLayout(self)
layout.addWidget(self._labelFormula, 0, 0)
layout.addWidget(self._editFormula, 0, 1)
layout.addWidget(self._buttonCalc, 1, 1)
layout.addWidget(self._labelResult, 2, 0)
layout.addWidget(self._labelResult2, 2, 1)
# addWidget(row, col, rowspan, colspan):
layout.addWidget(self._listHistory, 3, 0, 2, 2)
layout.setRowStretch(4, 1)
self.connect(self._buttonCalc, SIGNAL("clicked()"), self.onClickCalc)
def onClickCalc(self):
"""Event handler for the button click
"""
try:
text = str(self._editFormula.text())
rc = str(eval(text))
self._labelResult2.setText(rc)
self._listHistory.addItem(text + " = " + rc)
except Exception as e:
self._labelResult2.setText("+++ " + repr(e))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
# Let's resize the window:
window.resize(480, 250)
window.show()
sys.exit(app.exec_())