Untitled
unknown
plain_text
a year ago
1.9 kB
4
Indexable
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QLineEdit, QVBoxLayout
from PyQt6.QtCore import Qt
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Calculator')
# Create a QVBoxLayout
vbox = QVBoxLayout()
# Create a display widget
self.display = QLineEdit()
self.display.setAlignment(Qt.AlignmentFlag.AlignRight)
self.display.setReadOnly(True)
vbox.addWidget(self.display)
# Create a grid layout for the buttons
grid = QGridLayout()
# Button labels
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
# Position buttons in the grid layout
positions = [(i, j) for i in range(4) for j in range(4)]
for position, name in zip(positions, buttons):
button = QPushButton(name)
button.clicked.connect(self.on_click)
grid.addWidget(button, *position)
# Add grid layout to the vbox layout
vbox.addLayout(grid)
# Set the main layout of the window
self.setLayout(vbox)
def on_click(self):
button = self.sender()
text = button.text()
if text == '=':
try:
result = eval(self.display.text())
self.display.setText(str(result))
except Exception as e:
self.display.setText('Error')
elif text == 'C':
self.display.clear()
else:
self.display.setText(self.display.text() + text)
if __name__ == '__main__':
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec())
Editor is loading...
Leave a Comment