新手求助各位大佬,关于PyQt5多线程的问题

发布于 2022-09-11 19:25:00 字数 6615 浏览 10 评论 0

我想实现GUI一打开就把爬取数据存入数据库后,显示在QTextBrowser里,并且里面的内容通过百度语音合成生成mp3文件存入文件夹中,但是我想在self.thread_2中调用time_text这个变量时会报错说,那我怎么在self.thread_1运行时中断self.thread_2待time_text有值时再运行self.thread_2,代码如下:

#GUI代码
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'D:\Financial helper\helper.ui'
#
# Created by: PyQt5 UI code generator 5.11.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(803, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.show_text = QtWidgets.QTextBrowser(self.centralwidget)
        self.show_text.setGeometry(QtCore.QRect(40, 40, 721, 361))
        self.show_text.setObjectName("show_text")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(570, 410, 189, 30))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.voice = QtWidgets.QCheckBox(self.widget)
        self.voice.setChecked(True)
        self.voice.setObjectName("voice")
        self.horizontalLayout.addWidget(self.voice)
        self.refresh = QtWidgets.QPushButton(self.widget)
        self.refresh.setObjectName("refresh")
        self.horizontalLayout.addWidget(self.refresh)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.voice.setText(_translate("MainWindow", "播放声音"))
        self.refresh.setText(_translate("MainWindow", "刷新"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

#功能代码
from PyQt5.QtWidgets import QApplication,  QMainWindow
from Ui_helper import Ui_MainWindow
from PyQt5.QtCore import QThread, pyqtSignal
from aip import AipSpeech
from urllib import request
import pymysql
import sys
import json
import re
import time


class MyThreadOne(QThread):
    signal = pyqtSignal()
    def __init__(self):
        super().__init__()
    def run(self):
        while True:
            self.signal.emit()
            self.sleep(60)
        

class MyThreadTwo(QThread):
    voice = pyqtSignal()
    def __init__(self):
        super().__init__()
    def run(self):
        while True:
            self.voice.emit()


class RefreshData(QMainWindow):
    time_text = ''
    def __init__(self,  parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.refresh.clicked.connect(self.spider)
        self.db = pymysql.connect("localhost","root","","gui" )
        self.cursor = self.db.cursor()
        self.thread_1 = MyThreadOne()
        self.thread_1.start()
        self.thread_1.signal.connect(self.spider)
        self.thread_2 = MyThreadTwo()
        self.thread_2.start()
        self.thread_2.voice.connect(self.aipsp(time_text))
    
    def search(self,  time, value):
        self.sql_search = "select newstime from savenews where newstime like'{0}%' and news='{1}'".format(time, value)
        self.db.ping(reconnect=True)
        self.cursor.execute(self.sql_search)
        results = self.cursor.fetchall()
        if results:
            return 1
        return 0

    
    def spider(self):
        count = 0
        url = 'http://zhibo.sina.com.cn/api/zhibo/feed?callback=jQuery111209224197941081635_1553654066481&page=1&page_size=10' \
          '&zhibo_id=152'
        headers = {
            "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.15'
                  ' Safari/537.36'
        }
        regex = re.compile('({"result".*\[]}}}})')
        req = request.Request(url, headers=headers)
        rsp = request.urlopen(req)
        json_data = rsp.read().decode('utf-8')
        regex_data = re.search(regex, json_data).group()
        data = json.loads(regex_data)
        for i in range(9, -1, -1 ):
            count += 1
            text = data['result']['data']['feed']['list'][i]['rich_text']
            time = data['result']['data']['feed']['list'][i]['create_time']
            sql_insert = "insert into savenews values('{0}', '{1}');".format(time,  text)
            t_time = time.split(' ')
            try:
                if self.search(t_time[0], text):
                    if count == 9:
                        self.ui.show_text.append('--------------------------------------暂无更新内容-------------------------------------\n')
                    continue
                else:
                    self.db.ping(reconnect=True)
                    self.cursor.execute(sql_insert)
                    self.db.commit()
                    time_text += (time+text)
            except:
                self.db.rollback()
            self.db.close()
            self.ui.show_text.append('['+time+']:'+text+'\n')


    def aipsp(self, text):
        APP_ID = '******'
        API_KEY = '*****************'
        SECRET_KEY = '*****************'

        client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

        result = client.synthesis(text, 'zh', 1, {'vol': 3, 'pit':9})

        # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
        if not isinstance(result, dict):
            with open(r'D:\Financial helper\mp3\auido.mp3', 'ab') as f:
                f.write(result)
            self.time_text = ''
        else:
            with open(r'D:\Financial helper\mp3\diary\diary.txt', 'a') as f:
                f.write(time.ctime())
                f.write('   ')
                f.write(str(result['err_no']))
                f.write('   ')
                f.write(result['err_msg'])
                f.write('\n')

if __name__=='__main__':
    app = QApplication(sys.argv)
    win = RefreshData()
    win.show()
    sys.exit(app.exec_())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文