-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcalculator.py
90 lines (71 loc) · 2.5 KB
/
calculator.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
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from calculator_design import Ui_MainWindow
# pyuic5 -x calculator_design.ui -o calculator_design.py
class Calculator(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
for button in self.ui.numbers.buttons():
button.clicked.connect(self.add_digit)
for button in self.ui.operations.buttons():
button.clicked.connect(self.operation)
self.ui.clear.clicked.connect(self.clear_lcd)
self.ui.equals.clicked.connect(self.equals)
self.ui.dot.clicked.connect(self.add_dot)
self.operation = None
self.new_operation = False
self.number_string = '0'
self.A = 0
self.B = 0
self.show()
def add_digit(self):
if len(self.number_string) >= 8:
return
number = self.sender().objectName().split('_')[1]
if self.number_string == '0':
self.number_string = number
else:
self.number_string += number
self.ui.lcd.display(self.number_string)
def add_dot(self):
if '.' not in self.number_string:
self.number_string += '.'
print(self.number_string)
def operation(self):
self.operation = self.sender().objectName()
self.new_operation = True
self.A = float(self.number_string)
self.number_string = '0'
def equals(self):
if self.operation == None:
print('empty')
return
if self.new_operation:
self.B = float(self.number_string)
try:
if self.operation == 'add':
self.A += self.B
if self.operation == 'subtract':
self.A -= self.B
if self.operation == 'multiply':
self.A *= self.B
if self.operation == 'divide':
self.A /= self.B
except ArithmeticError:
error_dialog = QtWidgets.QMessageBox()
error_dialog.setText('Invalid operation')
error_dialog.exec_()
self.A = 0
self.number_string = '0'
self.ui.lcd.display(self.A)
self.previous_operation = self.operation
self.new_operation = False
def clear_lcd(self):
self.number_string = '0'
self.ui.lcd.display('0')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Calculator()
sys.exit(app.exec_())