-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
69 lines (58 loc) · 1.77 KB
/
Copy pathmain.py
File metadata and controls
69 lines (58 loc) · 1.77 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
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QGridLayout, QLineEdit, QPushButton
import qdarkstyle
from functools import partial
import math
def on_button_click(text):
current_text = input_box.text()
if text == "=":
try:
result = eval_expression(current_text)
input_box.setText(str(result))
except Exception as e:
input_box.setText("Erreur")
elif text == "C":
input_box.clear()
else:
input_box.setText(current_text + text)
def on_enter_pressed():
on_button_click("=")
def eval_expression(expression):
safe_dict = {"__builtins__": None, "math": math}
try:
return eval(expression, safe_dict)
except Exception as e:
raise e
app = QApplication(sys.argv)
app.setStyleSheet(qdarkstyle.load_stylesheet())
window = QWidget()
window.setWindowTitle("Calculator")
window.resize(300, 400)
layout = QVBoxLayout()
input_box = QLineEdit()
input_box.setPlaceholderText("Enter your mathematical expression")
input_box.setStyleSheet("font-size: 18px;")
input_box.returnPressed.connect(on_enter_pressed)
layout.addWidget(input_box)
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"(", ")", "C"
]
button_grid_layout = QGridLayout()
button_row, button_column = 0, 0
for button_text in buttons:
button = QPushButton(button_text)
button.setStyleSheet("font-size: 20px;")
button.clicked.connect(partial(on_button_click, button_text))
button_grid_layout.addWidget(button, button_row, button_column)
button_column += 1
if button_column > 3:
button_column = 0
button_row += 1
layout.addLayout(button_grid_layout)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())