用Python和PYQT5写一个“背单词神器”

安装Pyqt5

①pip install PyQt5

②需要安装Qt工具,也选择pip安装:

pip install PyQt5-tools

主程序

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow

import recit

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = recit.Ui_heheda()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

recit.py文件

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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QCoreApplication
from PyQt5.Qt import *
########背景设置##########
# encoding:utf-8
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# 背景设置部分
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtWidgets import QLabel, QPushButton, QFileDialog


class Ui_heheda(QWidget):
    def __init__(self):
        super(Ui_heheda, self).__init__()
        self.bool = False
        self.line_list = []
        self.w = ''
        self.Chinese = ''
        self.word = ''
        self.error_1 = []
        self.error_2 = []
        self.n = 0


    def setupUi(self, heheda):
        heheda.setObjectName("heheda")
        # heheda.resize(821, 600)
        heheda.resize(800, 600)
        image = QtGui.QPixmap()
        image.load(r"pig.png")
        palette1 = QtGui.QPalette()
        palette1.setBrush(heheda.backgroundRole(), QtGui.QBrush(image))  # 背景图片
        heheda.setPalette(palette1)
        heheda.setAutoFillBackground(True)
        # self.grabKeyboard()
        self.textEdit = QtWidgets.QTextEdit(heheda)
        self.textEdit.setGeometry(QtCore.QRect(50, 90, 711, 111))
        self.textEdit.setObjectName("textEdit")
        self.textEdit.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px;")
        self.textEdit.setText(self.Chinese)

        self.textEdit_2 = QtWidgets.QTextEdit(heheda)
        self.textEdit_2.setGeometry(QtCore.QRect(50, 210, 191, 111))
        self.textEdit_2.setObjectName("textEdit_2")
        self.textEdit_2.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        # self.textEdit_2.setText(word)
        # self.textEdit_2.toPlainText()

        self.textEdit_4 = QtWidgets.QTextEdit(heheda)
        self.textEdit_4.setGeometry(QtCore.QRect(310, 210, 451, 111))
        self.textEdit_4.setObjectName("textEdit_4")
        self.textEdit_4.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px;")

        self.textEdit_3 = QtWidgets.QTextEdit(heheda)
        self.textEdit_3.setGeometry(QtCore.QRect(300, 30, 211, 41))
        self.textEdit_3.setObjectName("textEdit_3")
        self.textEdit_3.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton = QtWidgets.QPushButton(heheda)
        self.pushButton.setGeometry(QtCore.QRect(50, 350, 191, 61))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.click_success)
        self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton_2 = QtWidgets.QPushButton(heheda)
        self.pushButton_2.setGeometry(QtCore.QRect(310, 350, 191, 61))
        self.pushButton_2.clicked.connect(self.click_continue)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton_3 = QtWidgets.QPushButton(heheda)
        self.pushButton_3.setGeometry(QtCore.QRect(570, 350, 191, 61))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.clicked.connect(self.click_exit)
        self.pushButton_3.clicked.connect(QCoreApplication.instance().quit)
        self.pushButton_3.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton_4 = QtWidgets.QPushButton(heheda)
        # self.pushButton_4.setGeometry(QtCore.QRect(90, 420, 100, 61))
        self.pushButton_4.setGeometry(QtCore.QRect(50, 420, 191, 61))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.click_filew)
        self.pushButton_4.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton_5 = QtWidgets.QPushButton(heheda)
        # self.pushButton_5.setGeometry(QtCore.QRect(615, 420, 100, 61))
        self.pushButton_5.setGeometry(QtCore.QRect(570, 420, 191, 61))
        self.pushButton_5.setObjectName("导入数据")
        self.pushButton_5.clicked.connect(self.click_data)
        self.pushButton_5.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")

        self.pushButton_6 = QtWidgets.QPushButton(heheda)
        self.pushButton_6.setGeometry(QtCore.QRect(310, 420, 191, 61))
        self.pushButton_6.setObjectName("pushButton_6")
        self.pushButton_6.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")
        self.pushButton_6.clicked.connect(self.click_answer)

        self.pushButton_7 = QtWidgets.QPushButton(heheda)
        self.pushButton_7.setGeometry(QtCore.QRect(50, 490, 191, 61))
        self.pushButton_7.setObjectName("pushButton_7")
        self.pushButton_7.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")
        self.pushButton_7.clicked.connect(self.click_error_txt)

        self.pushButton_8 = QtWidgets.QPushButton(heheda)
        self.pushButton_8.setGeometry(QtCore.QRect(310, 490, 191, 61))
        self.pushButton_8.setObjectName("pushButton_8")
        self.pushButton_8.setStyleSheet("background-color: rgb(255, 255, 255, 60);font-size:30px;border-radius:10px")
        self.pushButton_8.clicked.connect(self.click_reback)

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

    def retranslateUi(self, heheda):
        _translate = QtCore.QCoreApplication.translate
        heheda.setWindowTitle(_translate("heheda", "呵呵哒背单词神器!"))
        self.textEdit_3.setHtml(_translate("heheda",
                                           "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                           "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                           "p, li { white-space: pre-wrap; }\n"
                                           "</style></head><body style=\" font-family:\'宋体\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
                                           "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:12pt; font-weight:600;\">呵呵哒背单词!</span></p></body></html>"))
        self.pushButton.setText(_translate("heheda", "确定输入"))
        self.pushButton_2.setText(_translate("heheda", "继续练习"))
        self.pushButton_3.setText(_translate("heheda", "退出练习"))
        self.pushButton_4.setText(_translate("heheda", "导出数据"))
        self.pushButton_5.setText(_translate("heheda", "导入数据"))
        self.pushButton_6.setText(_translate("heheda", "查看答案"))
        self.pushButton_7.setText(_translate("heheda", "温习错背"))
        self.pushButton_8.setText(_translate("heheda", "闯关数据"))
    def click_success(self):
        import multiprocessing
        print("啊哈哈哈我终于成功了!")
        print('=--------------------------------=',self.word)
        I_input_text = self.textEdit_2.toPlainText()
        print('=--------------------------------=', I_input_text)
        if I_input_text.strip() == self.word.strip():
            # self.bool=True
            self.textEdit_4.setText("恭喜您回答正确!!!")
            self.textEdit_4.append(I_input_text)
            from PyQt5.QtWidgets import QApplication
            QApplication.processEvents()
            self.PaChong()
        else:
            self.textEdit_4.setText("很遗憾您答错了!正确答案是:")
            self.textEdit_4.append(self.word)
            self.error_1.append(self.word)
            self.error_2.append(self.Chinese)

        # self.my_thread.connect(self.click_display)
        # self.my_thread.word.connect(self.soud)
    def PaChong(self):
        import requests
        import os
        path = self.word + '.mp3'
        if not os.path.exists(path):
            h = requests.get(
                'https://sp0.baidu.com/-rM1hT4a2gU2pMbgoY3K/gettts?lan=en&text=' + self.word + '&spd=2&source=alading').content
            with open(path, 'wb') as  f:
                f.write(h)
        from playsound import playsound
        playsound(path)

    def click_continue(self):
        print("继续!")
        import random
        if len(self.line_list)==0:
            print("啥都没有")
        else:
            lst = []
            self.n=self.n+1
            if self.n==1:
                lst = self.line_list[0:50]
                random.shuffle(lst)
            if self.n==2:
                lst = self.line_list[50:100]
                random.shuffle(lst)
            if self.n==3:
                lst = self.line_list[100:150]
                # print(lst)
                random.shuffle(lst)
            if self.n==4:
                lst = self.line_list[150:-1]
                random.shuffle(lst)
                self.n=0
            lst = list(lst)
            if len(lst)==0:
                lst = self.line_list[0:50]

            lst = [i for i in lst if i != '\n']
            # print(lst)
            self.word_list = random.sample(lst, 1)
            print(self.word_list)
            self.w = self.word_list[0]
            # print(self.w)
            # print('============================', self.w.split(':')[:-2])
            self.word = self.w.split(':')[0]
            # print('============================', self.w.split(':')[0])
            print('============================',self.w.split(':')[1])
            self.Chinese = self.w.split(':')[1].strip('\n')
            self.textEdit.setText(self.Chinese)
            self.textEdit_2.setText(self.word)

        str = ''
        self.textEdit_2.setText(str)
        self.textEdit_4.setText(str)

    def click_exit(self):
        print("退出!")

    def click_data(self):
        my_file_path = QFileDialog.getOpenFileName(self, "打开文件", "/", "*.txt")
        print(my_file_path)
        file_object = open(my_file_path[0], 'r', encoding='UTF-8')
        self.textEdit_2.setText('')
        self.textEdit_4.setText('')
        self.line_list = []
        try:
            for line in file_object:
                self.line_list.append(line)

        finally:
            file_object.close()
        print(self.line_list)
        import random
        self.word_list = random.sample(self.line_list, 1)
        self.line_list = self.line_list
        self.w = self.word_list[0]
        self.word = self.w.split(':')[0]
        self.Chinese = self.w.split(':')[1].strip('\n')
        self.textEdit.setText(self.Chinese)
        print(self.word)
        print(self.Chinese)

    def click_filew(self):
        f = open("error.txt", "a+")
        for i in range(len(self.error_1)):
            f.write(self.error_1[i] +':'+ self.error_2[i] )
            f.write('\n')
        self.show_message()
        self.error_1 = []
        self.error_2 = []
        f.close()

    def show_message(self):
        QMessageBox.information(self, "标题", "成功导出背不熟单词",
                                QMessageBox.Yes)
    def click_answer(self):
        self.textEdit_4.setText(self.word)
        self.error_1.append(self.word)
        self.error_2.append(self.Chinese)

    def keyPressEvent(self, QKeyEvent):  # 键盘某个键被按下时调用
        # 参数1  控件
        from PyQt5.QtCore import Qt
        if QKeyEvent.modifiers()==Qt.ControlModifier and QKeyEvent.key()== Qt.Key_A: # 判断是否按下了A键
            # key()  是普通键
            print('按下了A键')
            self.click_answer()
        if QKeyEvent.modifiers()==Qt.ControlModifier and QKeyEvent.key()== Qt.Key_Z: # 判断是否按下了Z键
            # key()  是普通键
            print('按下了Z键')
            self.click_success()
        if QKeyEvent.modifiers()==Qt.ControlModifier and QKeyEvent.key()== Qt.Key_S: # 判断是否按下了S键
            # key()  是普通键
            print('按下了S键')
            self.click_continue()
    def click_error_txt(self):
        import random
        self.textEdit_2.setText('')
        self.textEdit_4.setText('')
        # file_object = open('error.txt', 'r', encoding='UTF-8' encoding="ISO-8859-1")
        file_object = open('error.txt', 'r', encoding="utf-8")
        self.line_list = []
        try:
            for line in file_object:
                self.line_list.append(line)
        finally:
            file_object.close()
        self.line_list = set(self.line_list)
        self.line_list = list(self.line_list)
        print("不重复",self.line_list)
        try:
            random.shuffle(self.line_list)
            word_list = random.sample(self.line_list, 1)
            self.w = word_list[0]
            self.word = self.w.split(':')[0].strip('\n')
            self.Chinese = self.w.split(':')[1].strip('\n')
            self.textEdit.setText(self.Chinese)
        except:
            print("can't")
            QMessageBox.information(self, "data", "没有错题词汇",
                                    QMessageBox.Yes)
    def click_reback(self):
        # ###################################################
        self.textEdit_2.setText('')
        self.textEdit_4.setText('')
        import random
        file_object = open('test.txt', 'r', encoding='UTF-8')
        self.line_list = []
        try:
            for line in file_object:
                self.line_list.append(line)
        finally:
            file_object.close()
        random.shuffle(self.line_list)
        word_list = random.sample(self.line_list, 1)
        self.w = word_list[0]
        self.word = self.w.split(':')[0]
        self.Chinese = self.w.split(':')[1].strip('\n')
        self.textEdit.setText(self.Chinese)
        # ###################################################
  • 演示视频转gif
    呵呵哒背单词神器

txt文本格式:

abandon:放弃 (棒)
aboard:在船,上船、
abroad:到国外,在国外
above:在...之上,高于
absent:缺席,不在
absolute:绝对的,完全的
absorb:吸收 吸引...的注意,使全神贯注
abstract:抽象的 摘要 梗概
abundant:丰富的,充裕的
accent:口音
access:接近,进入,通道
accommodation:住宿
accompany:陪伴,陪同,伴随,和...一起发生,为...伴奏
accomplish:完成,实现
according:按照,根据
account:叙述,说明,账户
accumulate:积累,积聚
accurate:准确的,精确的
accuse:指责,指控
accustomed:习惯的,惯常的
achieve:完成,实现;达到,得到
achievement:成绩,成就
acknowledge:承认,致谢
acquire:取得,获得,得到
across:横过,穿过;在...对面;宽,阔
act:行动;起作用;表演
active:行动,行动过程 (on)作用
actually:实际上
adapt:使适应,使适合;改编,改写
adequate:足够的,充足的;适当的,胜任的
adjust:调节,改变...以适应;校正,调整
admire:钦佩,赞赏,羡慕
admission:准许进入;承认,供认
adopt:收养;采取,采纳,采用
adult:成年人;成年的,成熟的
advance:前进,向前移动;取得进展;前进,进展;预付,预支
advanced:先进的,高级的
advantage:优点,优势;利益,好处
adventure:冒险,冒险活动;奇遇
advertise:登广告,宣扬
advertisement/ad:广告
affair:事情,事件
affect:影响;打动
afford:买得起,担负的起;提供,给予
afraid:害怕的,恐惧的;担心的
afterward:后来,以后
against:紧靠着;违反;和...对比
age:年龄;时代,时期;变老
agent:代理,代办
agency:代理,待办
agenda:会议事项;议事日程
agriculture:农业
ahead:在前,向前,提前
aid:援助,帮助;助手,辅助手段
aim:把...瞄准,把...对准;致力,旨在;瞄准,对准;目标,目的
air:空气,天空
aircraft:飞机,飞行器
airline:航空公司,航线
airport:机场
alarm:惊恐;报警器;使惊恐,向...报警
alcohol:酒精
alike:相像的
alive:活着的
allow:允许
allowance:津贴补助
almost:几乎,差不多
alphabet:字母表
already:早已经
alter:改变,变更
alternative:选择之事物;选择余地;二者选择其一的(*)
altogether:完全,全部;总而言之;总之,总共
always:总是,始终
amaze:使大为惊奇,使惊愕
ambassador:大使
ambition:有雄心的,野心勃勃的
amend:修正,修订(*)
amount:数量(*)
amuse:逗乐,逗笑;给...提供娱乐
analysis:分析;分解(e ei)
analyze:分析;分解(an)
ancestor:祖先;先驱者
ancient:古代的,古老的
anniversary:周年;周年纪念
announce:宣告,宣布
annoy:使恼怒,使烦恼
annual:每年的,年度的
anticipate:预期;希望(*)
anxiety:焦虑,忧虑;渴望
anxious:焦虑的,发愁的;渴望的,急切的
apart:分离,分开
apartment:公寓
apology:道歉,认错(n)
apologize:道歉(v)
apparent:表面上的,显然的
appeal:恳请,呼吁;上诉
appear:出现,显露;看起来,似乎
appearance:出现,露面;外观,外貌
appdendix:附录,附属物;阑尾(*)
appetite:食欲,胃口;欲望,爱好
appetizing:开胃的,刺激欲望的
applause:鼓掌,欢呼
apply:申请,请求;应用,运用;适用于
appliance:电气用具,装备(美[??pla??ns])(*)
applicant:申请,申请表;应用,实施
appoint:任命,委派;约定/指定(时间、地点)
appointment:约定/指定(时间、地点)
appreciate:重视,欣赏;领会,充分意识到;为..表示感激
appropriate:适当的(*)
approach:靠近,接近;途径,入门;方式,方法
approval:赞成,同意,认可,批准(n)
approve:赞成,同意;认可,批准(v)
April:四月
arbitration:仲裁,公断(*)
argue:争论,争辩
argument:争论,争辩;理由
arise:出现,发生;由...引起,起源于
arm:武器,军火;以武器装备;配备
army:军队;大群,大批
around:在周围,在附近;大约;在...附近
arouse:引起,激起,唤起;唤醒
arrange:安排,筹划;整理,排列,布置
arrest:逮捕,拘留
arrival:到来,到达(n)
arrive:到来,到达;达到,得出
arrow:箭状物
art:美术,艺术
article:文章,论文;条款,条文;件;
artificial:人工的,人造的,人为的;假的,矫揉造作的
artist:艺术家,美术家
ash:灰烬
Asia:亚洲
Asian:亚洲人的;亚洲的;亚洲人
aside:在旁边,到一边
asleep:睡着的
aspect:方面(*)
assess:对...进行评估,评价
assign:指派,选派;分配,布置(作业);指定(时间,地点等)
assignment:(分派的)任务;分配,指派
assist:帮助,协助
assistant:助手,助理;助教;助理的,辅助的
associate:协会,社团;联合,结合,交往,联想(*)
assume:假定,假设;承担(*)
assure:说服,使...相信;向...保证
astonish:使惊讶
athlete:运动员
Atlantic:大西洋的
atmosphere:大气,大气层;气氛
attach:系,贴,紧,装,连接;使成为一部分,使附属;使依(*)
attack:攻击,进攻
attempt:企图,试图
attend:出席,参加;照料,护理,专心于,致力于
attendant:服务员,伴随的,陪同的(*)
attention:注意,当心
attitude:态度,看法;姿势
attract:吸引,引起...的注意
audience:听众,观众,读者
August:八月
aunt:伯母,婶母...
Australia:澳大利亚,澳洲
Australian:澳大利亚人的;澳洲的,澳大利亚人
author:作者
authority:官方,当局,当权者,权力,权威
authorize:授权,委任
auto:汽车
automatic:自动的
automobie/auto:自动的
autumn:秋天,秋季
available:可利用的,可获得的;有空的,可取得联系的
avenue:林荫道,大街
average:平均数
avoid:避免,避开
await:等待,期待
awake:醒着的;唤醒,使觉醒
award:奖品,奖状;授予,给予
awful:可怕的;极度的,极坏的
awkward:粗苯的,笨拙的;令人尴尬的,棘手的

我是热爱学习,热爱编程的呵呵哒!如果你喜欢我的文章,不妨点个赞吧~

有疑问的话可以留言,我会尽我所能回答。

更多原创文章,尽请期待!

猜你喜欢

转载自blog.csdn.net/weixin_41987016/article/details/106131545