学习PyQt5的过程中尝试结合了一下qrcode,编写了一个图形化界面来生成自定义二维码,简单记录一下。
作为第一篇微信文章,也学习一下排版和文字设置。
代码如下:
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QLineEdit, QGridLayout, QLabel from PyQt5.QtCore import QCoreApplication from PyQt5.QtGui import QIcon from qrcode import QRCode, ERROR_CORRECT_H from PIL import Image
class Qr_qt(QWidget): def __init__(self): super().__init__() self.initUI()
def initUI(self): self.setWindowTitle("QR Code Maker") self.setWindowIcon(QIcon('10.jpg'))
self.lab1 = QLabel('Please Enter The Content Here') self.lab2 = QLabel(' Choose a Picture Here ') self.lab3 = QLabel(' Save The QR Code ')
self.text1 = QLineEdit('Content', self) self.text1.selectAll() self.text2 = QLineEdit('Picture', self) self.text3 = QLineEdit('Path', self)
self.bt1 = QPushButton('Create', self) self.bt1.setToolTip("<b>Push Here To Create QR Code</b>") self.bt1.clicked.connect(self.create_qr)
self.bt2 = QPushButton('Quit', self) self.bt2.setToolTip("<b>Push Here To Quit</b>") self.bt2.clicked.connect(QCoreApplication.instance().quit)
grid = QGridLayout() grid.addWidget(self.lab1, 0, 0) grid.addWidget(self.text1, 0, 1) grid.addWidget(self.lab2, 1, 0) grid.addWidget(self.text2, 1, 1) grid.addWidget(self.lab3, 2, 0) grid.addWidget(self.text3, 2, 1) grid.addWidget(self.bt1, 3, 0) grid.addWidget(self.bt2, 3, 1) self.setLayout(grid)
self.show()
def create_qr(self): qr = QRCode(version = 1, error_correction = ERROR_CORRECT_H, border = 2)
qr.add_data(self.text1.text()) qr.make(fit = True)
img = qr.make_image() img = img.convert("RGB") if self.text2.text(): try: logo = Image.open('{}'.format(self.text2.text()))
w, h = img.size logo_w = int(w/4) logo_h = int(h/4)
rel_w = int((w-logo_w)/2) rel_h = int((h-logo_h)/2) logo = logo.resize((logo_w, logo_h), Image.ANTIALIAS) logo = logo.convert("RGBA") img.paste(logo, (rel_w, rel_h), logo) except: QMessageBox.about(self, 'Error', 'No Such a File')
if self.text2.text() == None: pass
try: img.save('{}'.format(self.text3.text())) QMessageBox.about(self, 'Message', 'Successfully Created') except: QMessageBox.about(self, 'Error', 'Please Enter The Right Path')
if __name__ == '__main__': app = QApplication(sys.argv) qr = Qr_qt() sys.exit(app.exec_())
运行后的界面像这样:

完整的带注释的版本可以看发在CSDN博客上的,链接:
https://blog.csdn.net/pp5354chun/article/details/88408289
- THE END - ---------------------------------------------------------------------------------------------------------------------- 我们尊重原创,也注重分享,文章来源于微信公众号:秦小炅,建议关注公众号查看原文。如若侵权请联系qter@qter.org。 ----------------------------------------------------------------------------------------------------------------------
|