-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyCalc.py
More file actions
177 lines (149 loc) · 5.79 KB
/
PyCalc.py
File metadata and controls
177 lines (149 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#!/usr/bin/env python3
# Filename: pycalc.py
"""PyCalc is a simple calculator built using Python and PyQt5."""
import sys
# Import QApplication and the required widgets from PyQt5.QtWidgets
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from functools import partial
__version__ = '0.1'
__author__ = 'Chukwujioke Obinna'
# Create a subclass of QMainWindow to setup the calculator's GUI
class PyCalcUi(QMainWindow):
# Snip
def _createDisplay(self):
"""Create the display."""
# Create the display widget
self.display = QLineEdit()
# Set some display's properties
self.display.setFixedHeight(60)
self.display.setAlignment(Qt.AlignRight)
self.display.setReadOnly(True)
self.display.setStyleSheet('background-color:white')
# Add the display to the general layout
self.generalLayout.addWidget(self.display)
"""PyCalc's View (GUI)."""
def __init__(self):
"""View initializer."""
super().__init__()
# Set some main window's properties
self.setWindowTitle('PyCalc')
self.setFixedSize(300, 300)
self.setStyleSheet('background-color:#878787')
# Set the central widget
self.generalLayout = QVBoxLayout()
self._centralWidget = QWidget(self)
self.setCentralWidget(self._centralWidget)
self._centralWidget.setLayout(self.generalLayout)
# Create the display and the buttons
self._createDisplay()
self._createButtons()
def _createButtons(self):
"""Create the buttons."""
self.buttons = {}
buttonsLayout = QGridLayout()
# Button text | position on the QGridLayout
buttons = {'7': (0, 0),
'8': (0, 1),
'9': (0, 2),
'/': (0, 3),
'C': (0, 4),
'4': (1, 0),
'5': (1, 1),
'6': (1, 2),
'*': (1, 3),
'(': (1, 4),
'1': (2, 0),
'2': (2, 1),
'3': (2, 2),
'-': (2, 3),
')': (2, 4),
'0': (3, 0),
'00': (3, 1),
'.': (3, 2),
'+': (3, 3),
'=': (3, 4),
}
# Create the buttons and add them to the grid layout
for btnText, pos in buttons.items():
self.buttons[btnText] = QPushButton(btnText)
self.buttons[btnText].setFixedSize(43, 43)
buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
# Add buttonsLayout to the general layout
self.generalLayout.addLayout(buttonsLayout)
# Add colour to buttons
self.buttons[btnText].setStyleSheet(' QPushButton {background-color:#FFAAFF}'
'QPushButton {font:bold 12px}'
'QPushButton {font-family: SERIF ');
def setDisplayText(self, text):
"""Set display's text."""
self.display.setText(text)
self.display.setFocus()
def displayText(self):
"""Get display's text."""
return self.display.text()
def clearDisplay(self):
"""Clear the display."""
self.setDisplayText('')
# Create a Controller class to connect the GUI and the model
class PyCalcCtrl:
"""PyCalc Controller class."""
def __init__(self, model, view):
"""Controller initializer."""
self._evaluate = model
self._view = view
# Connect signals and slots
self._connectSignals()
def _calculateResult(self):
"""Evaluate expressions."""
result = self._evaluate(expression=self._view.displayText())
self._view.setDisplayText(result)
def _buildExpression(self, sub_exp):
"""Build expression."""
if self._view.displayText() == ERROR_MSG:
self._view.clearDisplay()
expression = self._view.displayText() + sub_exp
self._view.setDisplayText(expression)
def _connectSignals(self):
"""Connect signals and slots."""
for btnText, btn in self._view.buttons.items():
if btnText not in {'=', 'C'}:
btn.clicked.connect(partial(self._buildExpression, btnText))
self._view.buttons['='].clicked.connect(self._calculateResult)
self._view.display.returnPressed.connect(self._calculateResult)
self._view.buttons['C'].clicked.connect(self._view.clearDisplay)
ERROR_MSG = 'ERROR'
# Create a Model to handle the calculator's operation
def evaluateExpression(expression):
"""Evaluate an expression."""
try:
result = str(eval(expression, {}, {}))
except Exception:
result = ERROR_MSG
return result
# Client code
def main():
"""Main function."""
# Create an instance of QApplication
pycalc = QApplication(sys.argv)
# Show the calculator's GUI
view = PyCalcUi()
view.show()
# Create instances of the model and the controller
model = evaluateExpression
PyCalcCtrl(model=model, view=view)
# Execute the calculator's main loop
sys.exit(pycalc.exec_())
if __name__ == '__main__':
main()