-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleCalculatorPyQt1.py
342 lines (290 loc) · 16.1 KB
/
SimpleCalculatorPyQt1.py
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import sys
import os
# PyQt5 imports for building the graphical user interface (GUI)
from PyQt5.QtWidgets import (
QApplication,
QFileDialog,
QFormLayout,
QGridLayout,
QLabel,
QLineEdit,
QMessageBox,
QPushButton,
QTextEdit,
QWidget,
)
from PyQt5.QtGui import (
QFont,
QDoubleValidator,
QIcon,
QPixmap,
)
from PyQt5 import QtCore
# Import the Calculator class from a separate module (Calculator.py)
from Calculator import Calculator
# Set the locale to US English for formatting
locale = QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates)
class MainWindow(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# relative paths
dirname = os.path.dirname(__file__)
# Define paths for icon used in the application
calc_icon = os.path.join(dirname, 'calc_icon.png')
# Set window title and icon
self.setWindowTitle('PyQt Calculator')
self.setWindowIcon(QIcon(calc_icon))
self.setStyleSheet("""QWidget{background-color: #D8D6E6;}
QToolTip {
border: 1px solid darkgrey;
background-color: #0B132B;
border-radius: 10px;
color: white; }""")
self.calculator = Calculator()
# create a layout
self.layout = QFormLayout()
self.setLayout(self.layout)
self.label = QLabel('0.0')
self.label.setFont(QFont('Arial', 14))
self.label.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
self.label.setAlignment(QtCore.Qt.AlignRight)
self.layout.addRow('Result:', self.label)
# Create a validator to restrict input to numbers within a range
validator = QDoubleValidator(-10000000,10000000,5)
# Set the validator's locale and notation for proper formatting
locale = QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates)
validator.setLocale(locale)
validator.setNotation(QDoubleValidator.StandardNotation)
# Create text boxes for entering numbers
self.textbox1 = QLineEdit(self)
self.textbox1.setToolTip("<b>Please, enter Number 1!</b>")
self.textbox1.setFont(QFont('Arial', 12))
self.textbox1.setValidator(validator)
self.textbox1.setAlignment(QtCore.Qt.AlignRight)
self.textbox1.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
self.layout.addRow('Number 1:', self.textbox1)
self.textbox2 = QLineEdit(self)
self.textbox2.setToolTip("<b>Please, enter Number 2!</b>")
self.textbox2.setFont(QFont('Arial', 12))
self.textbox2.setValidator(validator)
self.textbox2.setAlignment(QtCore.Qt.AlignRight)
self.textbox2.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
self.layout.addRow('Number 2:', self.textbox2)
# Create a text box for displaying calculation history
self.history = QTextEdit()
self.history.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
self.layout.addRow('History:', self.history)
# Create a grid layout for arranging buttons
self.layout_button = QGridLayout()
self.layout.addRow(self.layout_button)
# Define button titles and create buttons
titles = ['Sum', 'Difference', 'Product', 'Quotient', 'History Save', 'Input Clear',
'History Clear', 'Exit']
buttons = [QPushButton(title) for title in titles]
# Set stylesheet for buttons (background color and text color)
for button in buttons:
button.setStyleSheet("""QPushButton {background-color: #0B132B;
color: white;
border-radius: 10px;
padding: 10px 15px;
margin-top: 0px;
outline: 0px;}
QPushButton:hover {background-color: #7F2982 }
""")
# Set tooltips and functionality for each button:
# Sum button calculates the sum and updates display and history
buttons[0].setToolTip("<b>Sum = Number 1 + Number 2</b>")
buttons[0].clicked.connect(lambda: self.calculate('sum'))
self.layout_button.addWidget(buttons[0],0,0)
# Difference button calculates the difference and updates display and history
buttons[1].setToolTip("<b>Difference = Number 1 - Number 2</b>")
buttons[1].clicked.connect(lambda: self.calculate('diff'))
self.layout_button.addWidget(buttons[1],0,1)
# Product button calculates the product and updates display and history
buttons[2].setToolTip("<b>Product = Number 1 * Number 2</b>")
buttons[2].clicked.connect(lambda: self.calculate('prod'))
self.layout_button.addWidget(buttons[2],1,0)
# Quotient button calculates the quotient and updates display and history
buttons[3].setToolTip("<b>Quotient = Number 1 / Number 2</b>")
buttons[3].clicked.connect(lambda: self.calculate('quot'))
self.layout_button.addWidget(buttons[3],1,1)
# Save History button saves the history to a text file
buttons[4].setToolTip("<b>Press button for save history as file: history_calc.txt</b>")
buttons[4].clicked.connect(lambda: self.save_history())
self.layout_button.addWidget(buttons[4],2,0)
# Clear Input button clears the input fields
buttons[5].setToolTip("<b>Press button for clear input!</b>")
buttons[5].clicked.connect(lambda: self.clear_input())
self.layout_button.addWidget(buttons[5],2,1)
# Clear History button clears the history text box
buttons[6].setToolTip("<b>Press button for clear history!</b>")
buttons[6].clicked.connect(lambda: self.clear_history())
self.layout_button.addWidget(buttons[6],3,0)
# Exit button closes the application
buttons[7].setToolTip("<b>Press button for closing app!</b>")
buttons[7].clicked.connect(app.exit)
self.layout_button.addWidget(buttons[7],3,1)
self.show()
def save_history(self):
"""
Saves the calculator history to a text file with a dialog for selecting location and name.
Checks if the history is empty and displays a message box if so.
"""
dirname = os.path.dirname(__file__)
warning = os.path.join(dirname, 'warning.png')
info = os.path.join(dirname, 'info.png')
# Check if history is empty
if not self.history.toPlainText():
messagebox = QMessageBox(QMessageBox.Warning, "Save History",
"History is empty! Cannot save an empty file.",
buttons=QMessageBox.Ok, parent=self)
messagebox.setIconPixmap(QPixmap(warning))
messagebox.findChild(QPushButton).setStyleSheet("""QPushButton {background-color: #0B132B;
color: white;
border-radius: 10px;
padding: 10px 15px;
margin-top: 0px;
outline: 0px;
min-width: 100px;}
QPushButton:hover {background-color: #7F2982 }
""")
messagebox.exec_()
return # Early return to prevent further execution if history is empty
# Get the selected file path
# This line opens a dialog for the user to choose a file for saving.
# The return value is a tuple containing the chosen file path.
filepath, _ = QFileDialog.getSaveFileName(self, 'Save File', '', 'Text files (*.txt)')
# Check if the user selected a file (file path is not empty)
if filepath:
# Open the file in write mode with UTF-8 encoding
with open(filepath, mode='w', encoding='utf-8') as history_file:
print(self.history.toPlainText(), file=history_file)
# Show a success message box
messagebox = QMessageBox(QMessageBox.Information, "Save History", "History successfully saved to file: " + filepath, buttons=QMessageBox.Ok, parent=self)
messagebox.setIconPixmap(QPixmap(info))
messagebox.findChild(QPushButton).setStyleSheet("""QPushButton {background-color: #0B132B;
color: white;
border-radius: 10px;
padding: 10px 15px;
margin-top: 0px;
outline: 0px;
min-width: 100px;}
QPushButton:hover {background-color: #7F2982 }
""")
messagebox.exec_()
def clear_history(self):
self.history.clear()
def clear_input(self):
self.label.setText('0.0')
self.textbox1.clear()
self.textbox2.clear()
def calculate(self, operation):
"""
Performs the calculation based on the operation and updates the display and history.
Args:
operation: The type of calculation to perform (e.g., "sum", "diff", "prod", "quot").
Raises:
ValueError: If no input is provided.
ZeroDivisionError: If division by zero is attempted.
"""
dirname = os.path.dirname(__file__)
stop_writing = os.path.join(dirname, 'stop_writing.png')
try:
a = float(self.textbox1.text())
b = float(self.textbox2.text())
self.textbox1.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
self.textbox2.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 1px solid #7F2982;
min-height: 40px;
""")
if operation == 'sum':
res = self.calculator.add(a, b)
ope = ' + '
elif operation == 'diff':
res = self.calculator.subtract(a, b)
ope = ' - '
elif operation == 'prod':
res = self.calculator.multiply(a, b)
ope = ' * '
elif operation == 'quot':
res = self.calculator.divide(a, b)
ope = ' / '
else:
raise ValueError("Invalid operation") # Handle invalid operation
self.label.setText(str(res))
self.history.setText(str(a) + ope + str(b) + " = " + str(res) + "\n" + self.history.toPlainText())
except ValueError:
self.textbox1.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 4px solid #F7717D;
min-height: 40px;
""")
self.textbox2.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 4px solid #F7717D;
min-height: 40px;
""")
messagebox = QMessageBox(QMessageBox.Information, "Error", "Input can only be a number!", buttons=QMessageBox.Ok, parent=self)
messagebox.setIconPixmap(QPixmap(stop_writing))
messagebox.findChild(QPushButton).setStyleSheet("""QPushButton {background-color: #0B132B;
color: white;
border-radius: 10px;
padding: 10px 15px;
margin-top: 0px;
outline: 0px;
min-width: 100px;}
QPushButton:hover {background-color: #7F2982 }
""")
messagebox.exec_()
except ZeroDivisionError:
self.textbox2.setStyleSheet("""background-color : white;
color: #0B132B;
border-radius: 10px;
border: 4px solid #F7717D;
min-height: 40px;
""")
messagebox = QMessageBox(QMessageBox.Warning, "Error", "Division by zero is not allowed!", buttons=QMessageBox.Ok, parent=self)
messagebox.setIconPixmap(QPixmap(stop_writing))
messagebox.findChild(QPushButton).setStyleSheet("""QPushButton {background-color: #0B132B;
color: white;
border-radius: 10px;
padding: 10px 15px;
margin-top: 0px;
outline: 0px;
min-width: 100px;}
QPushButton:hover {background-color: #7F2982 }
""")
messagebox.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())