0% found this document useful (0 votes)
34 views4 pages

Aplikasi

The document describes code for two Python GUI applications: 1. A mini calculator application built with PyQt that displays calculations and includes number buttons. 2. A simple text editor application with features like opening, saving, and closing files along with about menu options.

Uploaded by

ashadul umam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views4 pages

Aplikasi

The document describes code for two Python GUI applications: 1. A mini calculator application built with PyQt that displays calculations and includes number buttons. 2. A simple text editor application with features like opening, saving, and closing files along with about menu options.

Uploaded by

ashadul umam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Kalkulator mini

ketiklah sintaks berikut, lalu simpan dalam bentuk file


berekstensi py
In [ ]: import sys
from functools import partial

from PyQt6.QtCore import Qt


from PyQt6.QtWidgets import (
QApplication,
QGridLayout,
QLineEdit,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)

ERROR_MSG = "ERROR"
WINDOW_SIZE = 235
DISPLAY_HEIGHT = 35
BUTTON_SIZE = 40

class PyCalcWindow(QMainWindow):

def __init__(self):
super().__init__()
self.setWindowTitle("Mini Calculator")
self.setFixedSize(WINDOW_SIZE, WINDOW_SIZE)
self.generalLayout = QVBoxLayout()
centralWidget = QWidget(self)
centralWidget.setLayout(self.generalLayout)
self.setCentralWidget(centralWidget)
self._createDisplay()
self._createButtons()

def _createDisplay(self):
self.display = QLineEdit()
self.display.setFixedHeight(DISPLAY_HEIGHT)
self.display.setAlignment(Qt.AlignmentFlag.AlignRight)
self.display.setReadOnly(True)
self.generalLayout.addWidget(self.display)

def _createButtons(self):
self.buttonMap = {}
buttonsLayout = QGridLayout()
keyBoard = [
["7", "8", "9", "/", "C"],
["4", "5", "6", "*", "("],
["1", "2", "3", "-", ")"],
["0", "00", ".", "+", "="],
]

for row, keys in enumerate(keyBoard):


for col, key in enumerate(keys):
self.buttonMap[key] = QPushButton(key)
self.buttonMap[key].setFixedSize(BUTTON_SIZE, BUTTON_SIZE)
buttonsLayout.addWidget(self.buttonMap[key], row, col)

self.generalLayout.addLayout(buttonsLayout)

def setDisplayText(self, text):


self.display.setText(text)
self.display.setFocus()

def displayText(self):
return self.display.text()

def clearDisplay(self):
self.setDisplayText("")

def evaluateExpression(expression):
try:
result = str(eval(expression, {}, {}))
except Exception:
result = ERROR_MSG
return result

class PyCalc:

def __init__(self, model, view):


self._evaluate = model
self._view = view
self._connectSignalsAndSlots()

def _calculateResult(self):
result = self._evaluate(expression=self._view.displayText())
self._view.setDisplayText(result)

def _buildExpression(self, subExpression):


if self._view.displayText() == ERROR_MSG:
self._view.clearDisplay()
expression = self._view.displayText() + subExpression
self._view.setDisplayText(expression)

def _connectSignalsAndSlots(self):
for keySymbol, button in self._view.buttonMap.items():
if keySymbol not in {"=", "C"}:
button.clicked.connect(
partial(self._buildExpression, keySymbol)
)
self._view.buttonMap["="].clicked.connect(self._calculateResult)
self._view.display.returnPressed.connect(self._calculateResult)
self._view.buttonMap["C"].clicked.connect(self._view.clearDisplay)

def main():
pycalcApp = QApplication([])
pycalcWindow = PyCalcWindow()
pycalcWindow.show()
PyCalc(model=evaluateExpression, view=pycalcWindow)
sys.exit(pycalcApp.exec())

if __name__ == "__main__":
main()

Simpel teks editor


ketiklah sintaks berikut, lalu simpan dalam bentuk file
berekstensi py. Simpan filenya bersama dengan file icon.svg
dalam folder yang sama
In [ ]: from PyQt6.QtWidgets import *
from PyQt6.QtGui import QKeySequence, QAction

class MainWindow(QMainWindow):
def closeEvent(self, e):
if not text.document().isModified():
return
answer = QMessageBox.question(
window, None,
"Ada perubahan yang belum disimpan. Simpan sebelum menutup aplikasi?",
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel
)
if answer & QMessageBox.Save:
save()
if text.document().isModified():
e.ignore()
elif answer & QMessageBox.Cancel:
e.ignore()

app = QApplication([])
app.setApplicationName("Text Editor")
text = QPlainTextEdit()
window = MainWindow()
window.setCentralWidget(text)

file_path = None

menu = window.menuBar().addMenu("&File")
open_action = QAction("&Open")
def open_file():
global file_path
path = QFileDialog.getOpenFileName(window, "Open")[0]
if path:
text.setPlainText(open(path).read())
file_path = path
open_action.triggered.connect(open_file)
open_action.setShortcut(QKeySequence.StandardKey.Open)
menu.addAction(open_action)

save_action = QAction("&Save")
def save():
if file_path is None:
save_as()
else:
with open(file_path, "w") as f:
f.write(text.toPlainText())
text.document().setModified(False)
save_action.triggered.connect(save)
save_action.setShortcut(QKeySequence.StandardKey.Save)
menu.addAction(save_action)

save_as_action = QAction("Save &As...")


def save_as():
global file_path
path = QFileDialog.getSaveFileName(window, "Save As")[0]
if path:
file_path = path
save()
save_as_action.triggered.connect(save_as)
menu.addAction(save_as_action)

close = QAction("&Close")
close.triggered.connect(window.close)
menu.addAction(close)

help_menu = window.menuBar().addMenu("&Help")
about_action = QAction("&About")
help_menu.addAction(about_action)
def show_about_dialog():
text = "<center>" \
"<h1>Text Editor</h1>" \
"&#8291;" \
"<img src=icon.svg>" \
"</center>" \
"<p>Version 31.4.159.265358<br/>" \
"Copyright &copy; Company Inc.</p>"
QMessageBox.about(window, "About Text Editor", text)
about_action.triggered.connect(show_about_dialog)

window.show()
app.exec()

You might also like