Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from PyQt5.QtCore import Qt
- from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QLineEdit, QVBoxLayout
- class SimpleCalculator(QWidget):
- def __init__(self):
- super().__init__()
- self.initUI()
- def initUI(self):
- self.input_line = QLineEdit(self)
- self.input_line.setAlignment(Qt.AlignRight)
- self.input_line.setReadOnly(True)
- buttons = [
- '7', '8', '9', '/',
- '4', '5', '6', '*',
- '1', '2', '3', '-',
- '0', 'C', '=', '+'
- ]
- grid_layout = QGridLayout()
- row, col = 0, 0
- for button_text in buttons:
- button = QPushButton(button_text, self)
- button.clicked.connect(lambda _, ch=button_text: self.buttonClicked(ch))
- grid_layout.addWidget(button, row, col)
- col += 1
- if col > 3:
- col = 0
- row += 1
- main_layout = QVBoxLayout()
- main_layout.addWidget(self.input_line)
- main_layout.addLayout(grid_layout)
- self.setLayout(main_layout)
- self.setGeometry(300, 300, 300, 400)
- self.setWindowTitle('Kalkulator Sederhana')
- self.show()
- def buttonClicked(self, buttonText):
- if buttonText == '=':
- try:
- result = eval(self.input_line.text())
- self.input_line.setText(str(result))
- except Exception as e:
- self.input_line.setText('Error')
- elif buttonText == 'C':
- self.input_line.clear()
- else:
- current_text = self.input_line.text()
- new_text = current_text + buttonText
- self.input_line.setText(new_text)
- def main():
- app = QApplication(sys.argv)
- calculator = SimpleCalculator()
- sys.exit(app.exec_())
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement