# Excel dosyasını yükleyip grafik elde etmek.import sysimport matplotlibmatplotlib.use("Qt5Agg")import pandas as pdfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg,NavigationToolbar2QT as NavigationToolbarfrom matplotlib.figure import Figurefrom collections import Counterfrom functools import partialimport warningsclass help_(QWidget):def __init__(self):super().__init__()self.textEdit = QLabel('Excel dosyası ekleyiniz.\n''Cikis yapmak icin exit tiklayiniz.')self.layout = QHBoxLayout()self.layout.addWidget(self.textEdit)self.setLayout(self.layout)self.setWindowTitle('Help Window')self.setGeometry(350,200,200,100)class MplCanvas(FigureCanvasQTAgg):def __init__(self, parent=None, width=5, height=4, dpi=100) -> object:fig = Figure(figsize=(width, height), dpi=dpi)self.axes = fig.add_subplot(111)super(MplCanvas, self).__init__(fig)class analiz(QMainWindow):def __init__(self):super(analiz, self).__init__()self._createAction()self._cretaMenuBar()self._connectActions()def _cretaMenuBar(self):self.setWindowTitle("Loads Excel")self.setGeometry(200,190,770, 598)menuBar = self.menuBar()fileMenu = QMenu("&File", self)fileMenu.addAction(self.newAction)fileMenu.addAction(self.openAction)fileMenu.addAction(self.saveAction)fileMenu.addSeparator()fileMenu.addAction(self.exitAction)menuBar.addMenu(fileMenu)editMenu = menuBar.addMenu("&Edit")editMenu.addAction(self.copyAction)editMenu.addAction(self.pasteAction)editMenu.addAction(self.cutAction)editMenu.addSeparator()findMenu = editMenu.addMenu("Find and Replace")findMenu.addAction("Find...")findMenu.addAction("Replace...")graphMenu = menuBar.addMenu("Graph")graphMenu.addAction(self.graphMenuAction)helpMenu = menuBar.addMenu("&Help")helpMenu.addAction(self.aboutAction)self.openRecentMenu = fileMenu.addMenu("Open Recent")self.show()def _createAction(self):self.newAction = QAction("&New", self)self.openAction = QAction("&Open...", self)self.saveAction = QAction("&Save...", self)self.exitAction = QAction("&Exit...", self)self.copyAction = QAction("&Copy...", self)self.pasteAction = QAction("&Paste...", self)self.cutAction = QAction("&Cut...", self)self.aboutAction = QAction("&About...", self)self.newAction.setShortcut("Ctrl+N")self.openAction.setShortcut("Ctrl+O")self.saveAction.setShortcut("Ctrl+S")self.copyAction.setShortcut(QKeySequence.Copy)self.pasteAction.setShortcut(QKeySequence.Paste)self.copyAction.setShortcut(QKeySequence.Cut)self.graphMenuAction = QAction("Draw Graph", self)def _connectActions(self):self.newAction.triggered.connect(self.newFile)self.openAction.triggered.connect(self.openFile)self.saveAction.triggered.connect(self.saveFile)self.exitAction.triggered.connect(self.close)self.copyAction.triggered.connect(self.copyContent)self.pasteAction.triggered.connect(self.pasteContent)self.cutAction.triggered.connect(self.cutContent)self.aboutAction.triggered.connect(self.aboutContent)self.openRecentMenu.aboutToShow.connect(self.populateOpenRecent)self.graphMenuAction.triggered.connect(self.grafik)def newFile(self):self.centralWidget.setText("<b>File > New </b> Clicked")def openFile(self):# self.centralWidget.setText("<b>File > Open </b> Clicked")self.fname = QFileDialog.getOpenFileName(self, "Open File")self.file = ",".join(self.fname).split(",")[0].replace("/", "\\")# test = open(self.file, "r")# print(test)# with test:# text = pd.read_excel(self.file)# print(text)def saveFile(self):self.centralWidget.setText("<b>File > Save </b> Clicked")def copyContent(self):self.centralWidget.setText("<b>File > Copy </b> Clicked")def pasteContent(self):self.centralWidget.setText("<b>File > Paste </b> Clicked")def cutContent(self):self.centralWidget.setText("<b>File > Cut </b> Clicked")def aboutContent(self):# self.centralWidget.setText("<b>File > About </b> Clicked")self.w1 = help_()self.w1.show()def populateOpenRecent(self):self.openRecentMenu.clear()actions = []filenames = [f"File-{n}" for n in range(5)]for filename in filenames:action = QAction(filename, self)action.triggered.connect(partial(self.openRecentFile, filename))actions.append(action)self.openRecentMenu.addActions(actions)def grafik(self):with warnings.catch_warnings(record=True):warnings.simplefilter("always")self.df = pd.read_excel(self.file)text1, ok = QInputDialog.getText(self,'X Coords Start position', 'Enter Row Number')text2, ok = QInputDialog.getText(self,'X Coords Start position', 'Enter Column Number')# text3, ok = QInputDialog.getText(self,'Y Coords Start position', 'Enter Column Number')# text4, ok = QInputDialog.getText(self,'Y Coords Stop position', 'Enter Column Number')# text5, ok = QInputDialog.getText(self,'Y Coords start position', 'Enter Row Number')ok = Trueif ok:self.sutun = int(text2)self.satir = int(text1)self.namesRow = self.df.iloc[self.satir:, self.sutun]# self.basSutun = int(text3)# self.bitSutun = int(text4)# self.basSatir = int(text5)# self.values = self.veri.iloc[self.basSatir:,self.basSutun:self.bitSutun]x = Counter(self.namesRow)self.listt1 = []self.listt2 = []for value in set(self.namesRow):self.listt1.append(value)self.listt2.append(x[value])sc = MplCanvas(self, width=5, height=4, dpi=100)sc.axes.bar(self.listt1, self.listt2)# Grafikte degrleri yazmak için yapıldı.for i, txt in enumerate(self.listt2):sc.axes.annotate(txt, (self.listt1[i], self.listt2[i]))toolbar = NavigationToolbar(sc, self)layout = QVBoxLayout()layout.addWidget(toolbar)layout.addWidget(sc)widget = QWidget()widget.setLayout(layout)self.setCentralWidget(widget)self.show()if __name__ == '__main__':app = QApplication(sys.argv)w = analiz()app.exec_()
Bu Blogda Ara
9 Mayıs 2021 Pazar
Python ile Grafik Çizimi
25 Şubat 2021 Perşembe
Katalog Eser Ekleme-Arama-Silme-Güncelleme-Kayıtlı Olan Eserleri Sql Görüntüleme
import sys
import io
import folium
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sqlite3
class help_(QWidget):
def __init__(self):
super().__init__()
self.textEdit = QLabel('Eserleri eklemek icin eser menusunu tiklayiniz.\n'
'Navigasyon menusuden konum bilgilerine ulasabilirsiniz.\n'
'Cikis yapmak icin exit tiklayiniz.')
self.layout = QHBoxLayout()
self.layout.addWidget(self.textEdit)
self.setLayout(self.layout)
self.setWindowTitle('Help Window')
self.setGeometry(350,200,200,100)
class navigation(QWidget):
def __init__(self):
super(navigation, self).__init__()
self.setWindowTitle('Navigation')
self.setGeometry(200, 200, 600, 400)
coodinate = (41.02211977968873, 29.25890758913248)
m = folium.Map(
title='Sancaktepe',
zoom_start=15,
location=coodinate
)
# save map data to data object
data = io.BytesIO()
m.save(data, close_file=False)
webView = QWebEngineView()
webView.setHtml(data.getvalue().decode())
self.nav = QVBoxLayout()
self.nav.addWidget(webView)
self.setLayout(self.nav)
class viewSqlTable(QWidget):
def __init__(self):
super().__init__()
self.createTable()
def createTable(self):
self.setGeometry(200, 200, 350, 400)
self.tablo = QTableWidget()
self.layout = QHBoxLayout()
self.layout.addWidget(self.tablo)
self.setLayout(self.layout)
self.sqlTable()
def sqlTable(self):
self.connection = sqlite3.connect('catalog.db')
self.cur = self.connection.cursor()
find = "SELECT * FROM catalogs"
self.tabloIndex = 0
for row, row_data in enumerate(self.cur.execute(find)):
self.tablo.insertRow(row)
for col, col_data in enumerate(row_data):
if self.tabloIndex < 3:
self.tabloIndex += 1
self.tablo.setColumnCount(self.tabloIndex)
self.tablo.setItem(row, col, QTableWidgetItem(str(col_data)))
class searchSqlTable(QWidget):
def __init__(self):
super().__init__()
self.createTable()
def createTable(self):
self.setGeometry(200, 200, 345, 100)
self.tablo = QTableWidget()
self.layout = QHBoxLayout()
self.layout.addWidget(self.tablo)
self.setLayout(self.layout)
self.sqlTable()
def sqlTable(self):
self.baglanti = sqlite3.connect('catalog.db')
self.imlec = self.baglanti.cursor()
text1, ok = QInputDialog.getText(self, 'Search Eser', 'Enter Book Name')
self.eserAd = text1
find = 'SELECT * FROM catalogs WHERE eserAd = ?'
self.imlec.execute(find, (self.eserAd,))
eser = self.imlec.fetchall()
print(eser)
if len(eser) == 0:
print('There is no eser on the DB')
else:
self.tabloIndex = 0
for row, row_data in enumerate(eser):
self.tablo.insertRow(row)
for col, col_data in enumerate(row_data):
if self.tabloIndex < 3:
self.tabloIndex += 1
self.tablo.setColumnCount(self.tabloIndex)
self.tablo.setItem(row, col, QTableWidgetItem(str(col_data)))
self.baglanti.close()
class katalog(QMainWindow):
def __init__(self, eserAd=None, yazarAd=None, tarih=None):
super().__init__()
self.eserAd = eserAd
self.yazarAd = yazarAd
self.tarih = tarih
self.baglanti_olustur()
self.initUI()
self.w2 = navigation()
def __str__(self):
return '[EserAd: {0} | YazarAd: {1} | Tarih: {2}]'. \
format(self.eserAd, self.yazarAd, self.tarih)
def __repr__(self):
return '[EserAd: {0} | YazarAd: {1} | Tarih: {2}]'. \
format(self.eserAd, self.yazarAd, self.tarih)
def baglanti_olustur(self):
self.baglanti = sqlite3.connect('catalog.db')
self.imlec = self.baglanti.cursor()
tablo = 'CREATE TABLE IF NOT EXISTS catalogs(eserAd TEXT, yazarAd TEXT, tarih TEXT)'
self.imlec.execute(tablo)
self.baglanti.commit()
def baglanti_kes(self):
self.baglanti.close()
def initUI(self):
self.setWindowTitle('Katalog')
self.setGeometry(200, 200, 600, 400)
self.mainMenu = self.menuBar()
file = self.mainMenu.addMenu('Eser')
self.addeser = QAction('Eser Add', self)
self.addeser.triggered.connect(self.addEser)
self.searcheser = QAction('Search Eser', self)
self.searcheser.triggered.connect(self.searchEser)
self.vieweser = QAction('View Eser', self)
self.vieweser.triggered.connect(self.viewEser)
self.deleteeser = QAction('Delete Eser', self)
self.deleteeser.triggered.connect(self.deleteEser)
self.updateeser = QAction('Update Eser', self)
self.updateeser.triggered.connect(self.updateEser)
file.addAction(self.addeser)
file.addAction(self.searcheser)
file.addAction(self.vieweser)
file.addAction(self.deleteeser)
file.addAction(self.updateeser)
navMenu = self.mainMenu.addMenu('Navigation')
navMenu.addAction('Gmap')
navMenu.triggered.connect(self.navMap)
Help = self.mainMenu.addMenu('Help')
Help.addAction('Help')
Help.triggered.connect(self.Help)
exitAction = QAction('Exit', self)
exitAction.triggered.connect(qApp.quit)
exitButton = self.mainMenu.addMenu('Exit')
exitButton.addAction(exitAction)
label = QLabel(self)
pixmap = QPixmap('book.jpg')
label.setPixmap(pixmap)
label.setGeometry(0, 20, 600,400)
def Help(self):
self.w1 = help_()
self.w1.show()
def navMap(self):
self.w2.show()
def searchEser(self):
self.w4 = searchSqlTable()
self.w4.show()
def viewEser(self):
self.w3 = viewSqlTable()
self.w3.show()
def addEser(self):
self.baglanti = sqlite3.connect('catalog.db')
self.imlec = self.baglanti.cursor()
text1, ok = QInputDialog.getText(self, 'Add Eser', 'Enter Book Name')
text2, ok = QInputDialog.getText(self, 'Add Eser', 'Enter Author')
text3, ok = QInputDialog.getText(self, 'Add Eser', 'Enter Book Date')
if ok:
self.eserAd = text1
self.yazarAd = text2
self.tarih = text3
add = "INSERT INTO catalogs VALUES(?,?,?)"
self.imlec.execute(add, (self.eserAd, self.yazarAd, self.tarih))
self.baglanti.commit()
def deleteEser(self):
self.baglanti = sqlite3.connect('catalog.db')
self.imlec = self.baglanti.cursor()
text, ok = QInputDialog.getText(self, 'Delete Eser', 'Enter Book Name')
self.eserAd = text
find = 'DELETE FROM catalogs WHERE eserAd = ?'
self.imlec.execute(find, (self.eserAd,))
self.baglanti.commit()
def updateEser(self):
self.baglanti = sqlite3.connect('catalog.db')
self.imlec = self.baglanti.cursor()
text1, ok = QInputDialog.getText(self, 'Update Eser', 'Enter Update Book Name')
self.eserAd = text1
find = 'SELECT * FROM catalogs WHERE eserAd = ?'
self.imlec.execute(find, (self.eserAd,))
eser = self.imlec.fetchall()
if len(eser) == 0:
print('There is no eser on the DB')
else:
text1, ok = QInputDialog.getText(self, 'Update Eser', 'Enter New Book Name')
text2, ok = QInputDialog.getText(self, 'Update Eser', 'Enter New Book Author')
text3, ok = QInputDialog.getText(self, 'Update Eser', 'Enter New Book Date')
self.eserAd = text1
self.yazarAd = text2
self.tarih = text3
find2 = 'UPDATE catalogs SET eserAd=?, yazarAd=?, tarih=? WHERE eserAd = ? '
self.imlec.execute(find2, (self.eserAd, self.yazarAd, self.tarih, self.eserAd))
self.baglanti.commit()
app = QApplication(sys.argv)
ex = katalog()
ex.show()
sys.exit(app.exec_())
12 Aralık 2020 Cumartesi
Dosya İşlemleri (Ekleme-Arama-Silme)
import os
class patiensInfo:
def __init__(self, name=None, surname=None, patientId=None):
self.name = name,
self.surname = surname,
self.patientId = patientId,
self.filename='patient.txt'
def __str__(self):
return '[Name: {0} | Surname: {1} | PatientId: {2}]'.\
format(self.name, self.surname, self.patientId)
def __repr__(self):
return '[Name: {0} | Surname: {1} | PatientId: {2}]'.\
format(self.name, self.surname, self.patientId)
def patient_add(self):
self.name=input("Patient name: ")
self.surname = input("Patient surname: ")
self.patientId = input("Patient patientId: ")
try:
if os.path.exists(self.filename) and os.path.getsize(self.filename)>0:
myPatientDb= open(self.filename, 'a')
myPatientDb.write(self.name+" "+self.surname+" "+self.patientId+"\n")
else:
myPatientDb = open(self.filename, 'w')
myPatientDb.write(self.name+" "+self.surname+" "+self.patientId+"\n")
except IOError:
print("Bir hata oluştu!")
finally:
myPatientDb.close()
def displayPatients(self):
if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
myPatientDb = open(self.filename, 'r')
for records in myPatientDb:
print(records, end="")
myPatientDb.close()
def searchPatients(self):
if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
myPatientDb = open(self.filename, 'r')
try:
patientsSearch = input("Enter the patientId: ")
counter = 0
for patient in myPatientDb.readlines():
if patientsSearch == patient.split()[2]:
print(patient)
counter +=1
if counter == 0:
print("No record found whose name is:", patientsSearch)
except:
print("Error occured!")
else:
print("No record in patient.txt")
def deletePatient(self):
if os.path.exists(self.filename) and os.path.getsize(self.filename)>0:
myPatientDb = open(self.filename, 'r')
try:
patientsSearch = input("Enter the patientId: ")
counter = 0
liste = myPatientDb.readlines()
for patient in liste:
if patientsSearch == patient.split()[2]:
k = liste.index(patient)
del liste[k]
myPatientDb.close()
myPatientDb = open(self.filename, 'w')
myPatientDb.writelines(liste)
myPatientDb.close()
counter +=1
if counter == 0:
print("No record found whose name is:", patientsSearch)
except:
print("Error occured!")
else:
print("No record in patient.txt")
if __name__ == '__main__':
ourPatiens = patiensInfo()
print("Enter 1.To add 2.For search 3.Display 4.Delete 5.Exit")
while True:
choice = input("Enter your choice: ").lower()
if choice == "1":
ourPatiens.patient_add()
elif choice == "2":
ourPatiens.searchPatients()
elif choice == "3":
ourPatiens.displayPatients()
elif choice == "4":
ourPatiens.deletePatient()
elif choice == 'q':
exit()
else:
print("Invalid option. Try again!")
27 Ekim 2020 Salı
Yıldız Ücgen Cizimi
# def yildiz(level):
# for i in range(0,level):
# print(" " * (level-i), end="")
# print("*" * (2*i-1))
#
# yildiz(7)
class yildiz(object):
def __init__(self):
self.deger = 0
def show(self, sayi):
self.deger = sayi
for i in range(0, self.deger+1):
print(" " * (self.deger-i), end="")
print("*" * (2*i-1))
if __name__ == '__main__':
userInput = int(input("Deger: "))
result = yildiz()
result.show(userInput)
25 Ekim 2020 Pazar
Asansör Kontrol Paneli
from time import sleep
print(" Wellcome ".center(60,"*"))
print("Please enter the number floor.")
class elevatorControlPanel:
def __init__(self):
self.sayac = 0
def whichFloor(self):
self.floorNumber = input("\nEnter the number floor: ")
if self.floorNumber == "":
quit()
else:
return int(self.floorNumber)
def get_number(self, number):
if self.numberFloor == 0:
if self.sayac < self.numberFloor:
print("Elevator is going up {}.Floor".format(self.numberFloor))
sleep(self.sayac / 2)
self.sayac = self.numberFloor
return print("{}.Floor".format(self.numberFloor))
else:
print("Elevator is going down {}.Floor".format(self.numberFloor))
sleep(self.sayac / 2)
self.sayac = self.numberFloor
return print("{}.Floor".format(self.numberFloor))
elif self.sayac < self.numberFloor:
self.sayac = self.numberFloor
print("Elevator is going up {}.Floor".format(self.numberFloor))
sleep(self.sayac/2)
return print("{}.Floor".format(self.numberFloor))
# print("{}.floor".format(self.numberFloor))
# return quit() #İf you want end of elevator all the floor
elif self.sayac > self.numberFloor:
self.sayac = self.numberFloor
print("Elevator is going down {}.Floor".format(self.numberFloor))
sleep(self.sayac/2)
return print("{}.Floor".format(self.numberFloor))
# print("{}.floor".format(self.numberFloor))
# return quit() #İf you want end of elevator all the floor
else:
print("Enter number the floor.")
quit()
def Loop(self):
while True:
self.numberFloor = self.whichFloor()
self.floor = self.get_number(self.numberFloor)
# def showScreen(self):
# message = "\nYou are goin to {}.floor"
# print(message.format(self.numberFloor))
def calistir(self):
self.loop = self.Loop()
if __name__ == '__main__':
floor = elevatorControlPanel()
floor.calistir()
23 Ekim 2020 Cuma
Quiz Osmanli Padişahları
import random
osmanli = ["Osman Gazi", "Orhan Gazi", "I.Murat", "I.Bayezid", "I.Mehmed","II.Murat", "II.Mehmed", "II.Bayezid","I.Selim", "I.Süleyman","II.Selim", "III.Murad", "III.Mehmed", "I.Ahmed", "I.Mustafa","II.Osman", "IV.Murad","İbrahim","IV.Mehmed", "II.Süleyman","II.Ahmed", "II.Mustafa", "III.Ahmed", "I.Mahmud","III.Osman","III.Mustafa","I.Abdülhamid","III.Selim", "IV.Mustafa","II.Mahmud","Abdülmecid", "Abdülaziz", "V.Murad","II.Abdülhamid","V.Mehmed", "VI.Mehmed"]print(len(osmanli), "Osmanlı padişahı vardır.")print("Bu padişahlardan 10 tanesi için soru sorulacaktır.\nYanlış cevap verdiğinizde yarışma sonlanacaktır.\nHer doğru cevap 10 puandır. Hazırsanız başlayalım.")puan = 0soru = []siklar = ["a", "b", "c", "d"]while True:for i in range(1, 11):soruTipi = random.randrange(1, 3)if soruTipi == 1:soru = random.sample(osmanli, 1)x =[i for i in range(osmanli.index(*soru), osmanli.index(*soru) + 4)]random.shuffle(x)# print(osmanli.index(*soru) + 1) #Kopyaprint("{0}. Soru: {1} kaçıncı padişahtır".format(i, *soru))for k, j in zip(siklar, x):print("{}-) {} ".format(k, j), end="")print()cevap = input("")if cevap == "":print("Soruları boş geçilemez lütfen cevap verin")print("{0}. Soru: {1} kaçıncı padişahtır".format(i, *soru))for k, j in zip(siklar, x):print("{}-) {} ".format(k, j), end="")print()cevap = input("")elif str(osmanli.index(*soru) + 1) == cevap:puan += 10else:breakelif soruTipi == 2:soru = random.sample(osmanli, 4)random.shuffle(soru)# print(soru[0]) # Kopyaprint("{0}.Soru: {1}.Osmanlı padişahı aşağıdakilerden hangisidir.".format(i, (osmanli.index(soru[0]) + 1)))for l, j in zip(siklar, soru):print("{}-){} ".format(l, j), end="")print()cevap = input("")if cevap == "":print("Soruları boş geçilemez lütfen cevap verin")print("{0}.Soru: {1}.Osmanlı padişahı aşağıdakilerden hangisidir.".format(i, (osmanli.index(soru[0]) + 1)))for l, j in zip(siklar, soru):print("{}-){} ".format(l, j), end="")print()cevap = input("")elif soru[0] == cevap:puan += 10else:breakprint("Puanınız: ", puan)break
Kaydol:
Kayıtlar (Atom)
Python Pyqt5 ile Hesap Makinası
from PyQt5.QtWidgets import * from PyQt5.QtGui import * from mainUI import * from PyQt5.QtCore import * import sys # ----------------------U...