基于PyQt5实现简易饮品自动售货机

记录一个最近Python课程的作业,编写一个简易的饮品自动售货机,购物者选择需要的饮品,通过使用购物卡的方式支付,支付成功后从出货口取出饮品。

使用环境:Python3.8.6 + PyQt5 5.15.4

搭建的界面GUI

在这里插入图片描述

使用的核心代码解析

载入商品操作:通过调用Fuc.py文件中的loadTxt()函数载入商品信息 然后对载入信息进行处理,剔除商品数量为0的数据,拼接成我们所需要的格式;设置相关按钮不可选/可选

# Fuc.py
def loadTxt():
    """
    载入本地load.txt文件
    :return: 字典 --> 商品名:[价钱,数量]
    """
    with open("load.txt", 'r', encoding='utf-8') as f:
        lst = f.read().split("\n")  # 读取本地load.txt内容
    dct = {}
    for i in lst[:-1]:  # 解析重组数据
        name, money, num = i.split(",")
        if int(num) != 0:  # 剔除卖完的饮品
            dct[name] = [int(money), int(num)]  # 重组后数据格式: {name:[money,num]}
    return dct

# mainWin.py
def load(self):
    """
        载入商品
        :return: None
        """
    self.load_dct = Fuc.loadTxt()  # 载入商品信息
    items = [key + "  " + str(value[0]) + "元" for key, value in self.load_dct.items()]  # 格式设置
    self.pushButton_load.setEnabled(False)  # 设置 [载入商品]不可选
    self.listWidget.addItems(items)  # 商品框载入商品条目信息
    self.pushButton_card.setEnabled(True)  # 设置 [查询余额]可选

本地load.txt文件格式:商品名称,价格,数量
在这里插入图片描述

插入购物卡:设置相关按钮不可选/可选,出现提示信息

# mainWin.py
def card(self):
    """
    插入购物卡
    :return: None
    """
    self.pushButton_card.setEnabled(False)  # 设置 [插入购物卡]不可选
    self.pushButton_search.setEnabled(True)  # 设置 [查询余额] 可选
    QMessageBox.information(None, "提示", "购物卡加载成功")
    self.cardLoad = 1  # 判断购物卡是否已经插入

查询购物卡余额:读取本地money.txt文件获取购物卡余额

#Fuc.py
def searchMoneyTxt():
    """
    查询余额
    :return: 余额 (int)
    """
    with open("money.txt", 'r') as f:
        return f.read().split(",")

# mainWin.py
def search(self):
    """
    查询余额
    :return:None
    """
    pwd = Fuc.searchMoneyTxt()  # 获取购物卡密码
    text = QInputDialog.getText(self, "输入密码", "请输入密码", QLineEdit.Normal)[0]  # 弹出密码输入框
    if text == pwd[1]:  # 判断密码是否正确
        s = "余额:" + str(pwd[0])
        QMessageBox.information(None, "提示", s)
    else:
        QMessageBox.warning(None, "警告", "密码错误")

本地money.txt文件格式:余额,购物卡密码
在这里插入图片描述

购入:将所选的商品添加至预购框中

# mainWin.py
def shop(self):
    """
    购入
    :return: None
    """
    item_text = self.listWidget.currentItem().text()  # 读取选中的商品
    self.listWidget_2.addItem(item_text)  # 添加至购物框

结算:先判断购物卡是否已经插入,遍历预购框中物品,初步计算购买总值比对余额

# Fuc.py
def writeMoneyTxt(money):
    """
    修改信用卡余额
    :param money: 余额
    :return:None
    """
    with open("money.txt", 'w', encoding='utf-8') as f:
        f.write(str(money)+",123123")

# mainWin.py
def checkoutCard(self):
    """
    结算
    :return:
    """
    if self.cardLoad == 0:  # 判断购物卡是否插入
        QMessageBox.warning(None, "警告", "请插入信用卡")
    else:
        items = [self.listWidget_2.item(i).text() for i in range(self.listWidget_2.count())]  # 读取购物框商品
        # itmes --> ['PEPSI百事可乐  10元', 'PEPSI百事可乐  10元']
        num = 0
        for item in items:
            num += int(item[-3:-1])  # 计算总额

        money = int(Fuc.searchMoneyTxt()[0])  # 读取余额
        if num > money:  # 判断余额是否充足
            QMessageBox.warning(None, "警告", "余额不足")
        else:
            end = money - num
            s = f"购买成功,已经扣除{end}元"
            Fuc.writeMoneyTxt(end)  # 写入结算后余额
            QMessageBox.information(None, "提示", s)
            self.listWidget_2.clear()  # 清除购物框内容

删除预购框中选中项

def delItem(self):
    """
    删除
    :return:None
    """
    selected_index = self.listWidget_2.currentRow()  # 获取当前项的位置
    self.listWidget_2.takeItem(selected_index)  # 删除当前项

其它函数:修改购买相应商品的数量

# Fuc.py
def saveLoadTxt(names):
    """
    修改商品数量
    :param names: 购物的商品名称[list]  示例:['PEPSI百事可乐  10元', '椰树COCONUTPALM  10元']
    :return:None
    """
    dct = loadTxt()  # 读取本地文件 [返回字典]
    for name in names:  # 遍历输入的列表
        newName = name.split("  ")[0]  # 重组数据
        dct[newName][-1] -= 1  # 修改对应数量
    txt = ""
    for key, value in dct.items():
        txt += f"{key},{value[0]},{value[1]}\n"  # 重组内容
    with open("load.txt", 'w', encoding="utf-8") as f:
        f.write(txt)  # 覆写load.txt文件
相关控件样式

在程序中,对按钮、列表框调用QSS代码修改样式,增加了鼠标悬停、点击变色等样式

button_style = 'QPushButton{' \
               'font: 10pt "微软雅黑";' \
               'color: #2f3640;' \
               'background-color: #f5f6fa;' \
               'border-color: #2f3640;' \
               'border-radius: 15px;' \
               'border-style: solid;' \
               'border-width: 2px;' \
               'padding: 5px;}' \
               'QPushButton:hover{' \
               'color: #FFFFFF;' \
               'background-color: #718093;' \
               'border-color: #2f3640;}' \
               'QPushButton:pressed,checked{' \
               'color: #FFFFFF;' \
               'background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #273c75, stop:1 #487eb0);}' \
               'QPushButton:disabled{' \
               'color: #FFFFFF;' \
               'background-color: #dcdde1;' \
               'border-color: #dcdde1;}'
title_style = 'font-family: 等线;font-weight:400;font-size:48px;line-height:14px;text-align:center;color:rgb(0, 0, 84);'
label_style = 'font-family: 等线;font-weight:10;font-size:16px;line-height:14px;text-align:center;color:rgb(0, 0, 84);'

完整代码

mainWin.py

from ui import Ui_Form
from sys import argv, exit
import Fuc
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QInputDialog, QLineEdit


class MainWin(QMainWindow, Ui_Form):
    def __init__(self):
        super(MainWin, self).__init__()
        self.setupUi(self)
        self.load_dct = {}
        self.cardLoad = 0  # 初始化购物卡信息
        self.pushButton_shop.setStyleSheet(Fuc.button_style)
        self.pushButton_shop.clicked.connect(self.shop)
        self.pushButton_card.setStyleSheet(Fuc.button_style)
        self.pushButton_card.setEnabled(False)
        self.pushButton_card.clicked.connect(self.card)
        self.pushButton_load.setStyleSheet(Fuc.button_style)
        self.pushButton_load.clicked.connect(self.load)
        self.pushButton_search.setStyleSheet(Fuc.button_style)
        self.pushButton_search.setEnabled(False)
        self.pushButton_search.clicked.connect(self.search)
        self.pushButton_del.setStyleSheet(Fuc.button_style)
        self.pushButton_checkout.setStyleSheet(Fuc.button_style)
        self.pushButton_checkout.clicked.connect(self.checkoutCard)
        self.pushButton_del.clicked.connect(self.delItem)

    def load(self):
        """
        载入商品
        :return: None
        """
        self.load_dct = Fuc.loadTxt()  # 载入商品信息
        items = [key + "  " + str(value[0]) + "元" for key, value in self.load_dct.items()]  # 格式设置
        self.pushButton_load.setEnabled(False)  # 设置 [载入商品]不可选
        self.listWidget.addItems(items)  # 商品框载入商品条目信息
        self.pushButton_card.setEnabled(True)  # 设置 [查询余额]可选

    def card(self):
        """
        插入购物卡
        :return: None
        """
        self.pushButton_card.setEnabled(False)  # 设置 [插入购物卡]不可选
        self.pushButton_search.setEnabled(True)  # 设置 [查询余额] 可选
        QMessageBox.information(None, "提示", "购物卡加载成功")
        self.cardLoad = 1  # 判断购物卡是否已经插入

    def search(self):
        """
        查询余额
        :return:None
        """
        pwd = Fuc.searchMoneyTxt()  # 获取购物卡密码
        text = QInputDialog.getText(self, "输入密码", "请输入密码", QLineEdit.Normal)[0]  # 弹出密码输入框
        if text == pwd[1]:  # 判断密码是否正确
            s = "余额:" + str(pwd[0])
            QMessageBox.information(None, "提示", s)
        else:
            QMessageBox.warning(None, "警告", "密码错误")

    def shop(self):
        """
        购入
        :return: None
        """
        item_text = self.listWidget.currentItem().text()  # 读取选中的商品
        self.listWidget_2.addItem(item_text)  # 添加至购物框

    def checkoutCard(self):
        """
        结算
        :return:
        """
        if self.cardLoad == 0:  # 判断购物卡是否插入
            QMessageBox.warning(None, "警告", "请插入信用卡")
        else:
            items = [self.listWidget_2.item(i).text() for i in range(self.listWidget_2.count())]  # 读取购物框商品
            # itmes --> ['PEPSI百事可乐  10元', 'PEPSI百事可乐  10元']
            print(items)
            num = 0
            for item in items:
                num += int(item[-3:-1])  # 计算总额

            money = int(Fuc.searchMoneyTxt()[0])  # 读取余额
            if num > money:  # 判断余额是否充足
                QMessageBox.warning(None, "警告", "余额不足")
            else:
                end = money - num
                s = f"购买成功,已经扣除{num}元"
                Fuc.writeMoneyTxt(end)  # 写入结算后余额
                Fuc.saveLoadTxt(items)  # 修改商品剩余数量
                QMessageBox.information(None, "提示", s)
                self.listWidget_2.clear()  # 清除购物框内容

    def delItem(self):
        """
        删除
        :return:None
        """
        selected_index = self.listWidget_2.currentRow()  # 获取当前项的位置
        self.listWidget_2.takeItem(selected_index)  # 删除当前项


if __name__ == '__main__':
    app = QApplication(argv)
    MainWindow = MainWin()
    MainWindow.show()
    exit(app.exec_())

Fuc.py

button_style = 'QPushButton{' \
               'font: 10pt "微软雅黑";' \
               'color: #2f3640;' \
               'background-color: #f5f6fa;' \
               'border-color: #2f3640;' \
               'border-radius: 15px;' \
               'border-style: solid;' \
               'border-width: 2px;' \
               'padding: 5px;}' \
               'QPushButton:hover{' \
               'color: #FFFFFF;' \
               'background-color: #718093;' \
               'border-color: #2f3640;}' \
               'QPushButton:pressed,checked{' \
               'color: #FFFFFF;' \
               'background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #273c75, stop:1 #487eb0);}' \
               'QPushButton:disabled{' \
               'color: #FFFFFF;' \
               'background-color: #dcdde1;' \
               'border-color: #dcdde1;}'
title_style = 'font-family: 等线;font-weight:400;font-size:48px;line-height:14px;text-align:center;color:rgb(0, 0, 84);'
label_style = 'font-family: 等线;font-weight:10;font-size:16px;line-height:14px;text-align:center;color:rgb(0, 0, 84);'


def loadTxt():
    """
    载入本地load.txt文件
    :return: 字典 --> 商品名:[价钱,数量]
    """
    with open("load.txt", 'r', encoding='utf-8') as f:
        lst = f.read().split("\n")  # 读取本地load.txt内容
    dct = {}
    for i in lst[:-1]:  # 解析重组数据
        name, money, num = i.split(",")
        if int(num) != 0:  # 剔除卖完的饮品
            dct[name] = [int(money), int(num)]  # 重组后数据格式: {name:[money,num]}
    return dct


def writeMoneyTxt(money):
    """
    修改信用卡余额
    :param money: 余额
    :return:None
    """
    with open("money.txt", 'w', encoding='utf-8') as f:
        f.write(str(money) + ",123123")


def saveLoadTxt(names):
    """
    修改商品数量
    :param names: 购物的商品名称[list]  示例:['PEPSI百事可乐  10元', '椰树COCONUTPALM  10元']
    :return:None
    """
    dct = loadTxt()  # 读取本地文件 [返回字典]
    for name in names:  # 遍历输入的列表
        newName = name.split("  ")[0]  # 重组数据
        dct[newName][-1] -= 1  # 修改对应数量
    txt = ""
    for key, value in dct.items():
        txt += f"{key},{value[0]},{value[1]}\n"  # 重组内容
    with open("load.txt", 'w', encoding="utf-8") as f:
        f.write(txt)  # 覆写load.txt文件


def searchMoneyTxt():
    """
    查询余额
    :return: 余额 (int)
    """
    with open("money.txt", 'r') as f:
        return f.read().split(",")

ui.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QIcon


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(328, 488)
        self.frame = QtWidgets.QFrame(Form)
        Form.setWindowIcon(QIcon("shop.ico"))
        self.frame.setGeometry(QtCore.QRect(90, 10, 131, 51))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.label = QtWidgets.QLabel(self.frame)
        self.label.setGeometry(QtCore.QRect(0, 0, 151, 51))
        self.label.setStyleSheet("font-family: 等线;font-weight:10;font-size:25px;line-height:14px;text-align:center;color:rgb(0, 0, 84);")
        self.label.setObjectName("label")
        self.pushButton_card = QtWidgets.QPushButton(Form)
        self.pushButton_card.setGeometry(QtCore.QRect(240, 212, 81, 31))
        self.pushButton_card.setObjectName("pushButton_card")
        self.listWidget = QtWidgets.QListWidget(Form)
        self.listWidget.setGeometry(QtCore.QRect(10, 70, 221, 221))
        self.listWidget.setObjectName("listWidget")
        self.pushButton_load = QtWidgets.QPushButton(Form)
        self.pushButton_load.setGeometry(QtCore.QRect(240, 72, 81, 31))
        self.pushButton_load.setObjectName("pushButton_load")
        self.pushButton_shop = QtWidgets.QPushButton(Form)
        self.pushButton_shop.setGeometry(QtCore.QRect(240, 120, 81, 31))
        self.pushButton_shop.setObjectName("pushButton_shop")
        self.listWidget_2 = QtWidgets.QListWidget(Form)
        self.listWidget_2.setGeometry(QtCore.QRect(10, 310, 311, 111))
        self.listWidget_2.setObjectName("listWidget_2")
        self.pushButton_search = QtWidgets.QPushButton(Form)
        self.pushButton_search.setGeometry(QtCore.QRect(240, 260, 81, 31))
        self.pushButton_search.setObjectName("pushButton_search")
        self.pushButton_del = QtWidgets.QPushButton(Form)
        self.pushButton_del.setGeometry(QtCore.QRect(10, 430, 75, 31))
        self.pushButton_del.setObjectName("pushButton_del")
        self.pushButton_checkout = QtWidgets.QPushButton(Form)
        self.pushButton_checkout.setGeometry(QtCore.QRect(110, 430, 75, 31))
        self.pushButton_checkout.setObjectName("pushButton_checkout")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "自动售卖机"))
        self.label.setText(_translate("Form", "自动售卖机"))
        self.pushButton_card.setText(_translate("Form", "插入购物卡"))
        self.pushButton_load.setText(_translate("Form", "载入商品"))
        self.pushButton_shop.setText(_translate("Form", "购入"))
        self.pushButton_search.setText(_translate("Form", "查询余额"))
        self.pushButton_del.setText(_translate("Form", "删除"))
        self.pushButton_checkout.setText(_translate("Form", "结算"))

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现PDF转DOC需要以下几个步骤: 1. 安装PyQt5和PaddleOCR,并导入相关模块: ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import Qt import paddleocr import docx ``` 2. 创建PyQt5界面,包括一个按钮和一个文本框: ```python class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(100, 100, 500, 300) self.setWindowTitle('PDF转DOC') self.btn = QPushButton('选择PDF文件', self) self.btn.move(200, 100) self.btn.clicked.connect(self.selectFile) self.textEdit = QTextEdit(self) self.textEdit.move(50, 150) self.textEdit.setReadOnly(True) ``` 3. 定义选择PDF文件的函数,并调用PaddleOCR进行OCR识别: ```python def selectFile(self): filename, _ = QFileDialog.getOpenFileName(self, '选择PDF文件', '', 'PDF files (*.pdf)') if filename: self.textEdit.clear() self.textEdit.insertPlainText('正在识别,请稍候...') QApplication.processEvents() ocr = paddleocr.OCR() result = ocr.ocr(filename, cls=True) self.textEdit.clear() doc = docx.Document() for line in result: if line[1][0] != '\n': doc.add_paragraph(line[1]) else: doc.add_paragraph(line[1][1:]) doc.save('result.docx') self.textEdit.insertPlainText('转换完成,已保存为result.docx') ``` 4. 运行PyQt5界面: ```python if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) ``` 完整代码如下:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Meaauf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值