Certainly! Below is a fully functional calculator using PyQt5 with a modern design (using QSS for styling), and an innovative feature: calculation history with clickable entries. Clicking a previous result will re-insert it into the input for further calculations.
Features:
- Modern flat design (dark mode)
- Responsive buttons
- Calculation history panel (click to reuse results)
- Keyboard support (numbers, operators, Enter, Backspace, etc.)
1. Install PyQt5
pip install PyQt5
2. The Code
import sys
from PyQt5.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton,
QListWidget, QListWidgetItem, QSizePolicy
)
from PyQt5.QtCore import Qt
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Modern PyQt Calculator")
self.setFixedSize(400, 500)
self.init_ui()
self.apply_styles()
def init_ui(self):
main_layout = QVBoxLayout(self)
main_layout.setSpacing(10)
main_layout.setContentsMargins(15, 15, 15, 15)
# Display
self.display = QLineEdit()
self.display.setReadOnly(True)
self.display.setAlignment(Qt.AlignRight)
self.display.setFixedHeight(50)
self.display.setPlaceholderText("0")
main_layout.addWidget(self.display)
# History
self.history = QListWidget()
self.history.setFixedHeight(100)
self.history.setFocusPolicy(Qt.NoFocus)
self.history.itemClicked.connect(self.history_item_clicked)
main_layout.addWidget(self.history)
# Buttons
buttons = [
['C', '(', ')', '⌫'],
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['0', '.', '=', '+'],
]
btn_layout = QVBoxLayout()
for row in buttons:
h = QHBoxLayout()
for btn_text in row:
btn = QPushButton(btn_text)
btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
btn.clicked.connect(self.button_clicked)
h.addWidget(btn)
btn_layout.addLayout(h)
main_layout.addLayout(btn_layout)
def apply_styles(self):
self.setStyleSheet("""
QWidget {
background: #23272e;
color: #f8f8f2;
font-family: 'Segoe UI', 'Arial', sans-serif;
font-size: 18px;
}
QLineEdit {
background: #282c34;
border: none;
border-radius: 8px;
padding: 10px;
font-size: 24px;
color: #f8f8f2;
}
QListWidget {
background: #21252b;
border: none;
border-radius: 8px;
font-size: 16px;
}
QListWidget::item {
padding: 6px 10px;
}
QListWidget::item:selected {
background: #44475a;
color: #50fa7b;
}
QPushButton {
background: #282c34;
border: none;
border-radius: 8px;
margin: 4px;
font-size: 20px;
min-width: 0px;
min-height: 0px;
padding: 12px;
color: #f8f8f2;
transition: background 0.2s;
}
QPushButton:hover {
background: #44475a;
}
QPushButton:pressed {
background: #6272a4;
}
QPushButton#equals {
background: #50fa7b;
color: #282c34;
}
""")
def button_clicked(self):
sender = self.sender()
text = sender.text()
if text == 'C':
self.display.clear()
elif text == '⌫':
self.display.setText(self.display.text()[:-1])
elif text == '=':
self.calculate()
else:
self.display.setText(self.display.text() + text)
def keyPressEvent(self, event):
key = event.key()
if key in (Qt.Key_0, Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4,
Qt.Key_5, Qt.Key_6, Qt.Key_7, Qt.Key_8, Qt.Key_9):
self.display.setText(self.display.text() + event.text())
elif key in (Qt.Key_Plus, Qt.Key_Minus, Qt.Key_Asterisk, Qt.Key_Slash, Qt.Key_ParenLeft, Qt.Key_ParenRight, Qt.Key_Period):
self.display.setText(self.display.text() + event.text())
elif key == Qt.Key_Backspace:
self.display.setText(self.display.text()[:-1])
elif key in (Qt.Key_Enter, Qt.Key_Return):
self.calculate()
elif key == Qt.Key_Escape:
self.display.clear()
def calculate(self):
expr = self.display.text()
if not expr.strip():
return
try:
# Safe eval: only allow numbers and operators
allowed = "0123456789+-*/(). "
if not all(c in allowed for c in expr):
raise ValueError("Invalid character")
result = eval(expr, {"__builtins__": None}, {})
self.display.setText(str(result))
# Add to history
item = QListWidgetItem(f"{expr} = {result}")
self.history.insertItem(0, item)
if self.history.count() > 10:
self.history.takeItem(self.history.count() - 1)
except Exception:
self.display.setText("Error")
def history_item_clicked(self, item):
# Extract result after '='
if '=' in item.text():
result = item.text().split('=')[-1].strip()
self.display.setText(self.display.text() + result)
if __name__ == "__main__":
app = QApplication(sys.argv)
calc = Calculator()
calc.show()
sys.exit(app.exec_())
3. How to Run
- Save the code as
modern_calculator.py
- Run:
python modern_calculator.py
What’s new?
- Clickable history: Click a previous result to append it to the current input.
- Modern dark design: Flat, rounded, and responsive.
- Keyboard support: For fast input.
You can further enhance it with scientific functions, themes, or export/import history!