[学習記録]電卓をつくる

Python
  • GUIはTinker以外にも沢山ある、とりあえずPyside6を勉強する
  • やっぱり最初は電卓。AIが30秒足らずで作った
import sys
from PySide6.QtWidgets import (
    QApplication,
    QWidget,
   QVBoxLayout,
    QGridLayout,
    QPushButton,
    QLineEdit,
)

class Calculator(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("電卓")
        self.resize(300, 400)

        layout = QVBoxLayout()

        self.display = QLineEdit()
        self.display.setReadOnly(True)
        self.display.setStyleSheet("font-size:20px;")
        layout.addWidget(self.display)

        grid = QGridLayout()

        buttons = [
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        ]

        row = 0
        col = 0

        for text in buttons:
            button = QPushButton(text)
            button.setMinimumHeight(60)

            if text == "=":
                button.clicked.connect(self.calculate)
            else:
                button.clicked.connect(
                    lambda checked=False, t=text: self.display.insert(t)
                )

            grid.addWidget(button, row, col)

            col += 1
            if col == 4:
                col = 0
                row += 1

        layout.addLayout(grid)

        clear_button = QPushButton("C")
        clear_button.setMinimumHeight(50)
        clear_button.clicked.connect(self.display.clear)

        layout.addWidget(clear_button)

        self.setLayout(layout)

    def calculate(self):
        try:
            result = str(eval(self.display.text()))
            self.display.setText(result)
        except Exception:
            self.display.setText("Error")

app = QApplication(sys.argv)

window = Calculator()
window.show()

app.exec()

コメント