我是靠谱客的博主 刻苦口红,最近开发中收集的这篇文章主要介绍【pyqt5 按钮点击事件获取不到参数更新后的值】上代码目前遇到的问题:先执行start_thread 后 BtnPusClick 方法里面获取到的isSpeak是False(初始化的值),实际上是在start_thread方法里面已经改为True,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

pyqt5 按钮点击事件获取不到参数更新后的值,求大神们指教

  • 上代码
  • 目前遇到的问题:先执行start_thread 后 BtnPusClick 方法里面获取到的isSpeak是False(初始化的值),实际上是在start_thread方法里面已经改为True

上代码

import pyttsx3
import threading
import os
import sys
import time
import random
import io
from PyQt5 import QtCore,QtGui
from PyQt5.QtWidgets import QWidget,QMenu, QSystemTrayIcon,QDesktopWidget,QAction, qApp,QApplication,QLabel,QLineEdit,QPushButton,QVBoxLayout,QHBoxLayout
from PyQt5.QtCore import Qt,QRect,QEvent,QPoint
from PyQt5.Qt import QCursor,QPropertyAnimation
from PyQt5.QtGui import QPalette,QColor, QIcon, QStatusTipEvent
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5 import QtWidgets
SCREEN_WEIGHT = 1920
SCREEN_HEIGHT = 1080
WINDOW_WEIGHT = 300
WINDOW_HEIGHT = 50
def System():
import platform
# help(platform)
# print(sys.getwindowsversion().build)
# print(platform.system())
# print(platform.version())
# print(platform.uname())
# print(platform.release())
# print(platform.python_version())
return platform.system()
def ToastShow(title= "toast" ,msg = "msg",duration = 0.5):
if System() != "Windows":
return
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast(title,msg,duration = duration)
print("ok")
return
from plyer import notification
notification.notify(
title= title,
message= msg,
# app_icon="tubiao.ico",
timeout= 0.1
)
class MySpeak(QThread):
"""docstring for MySpeak"""
code = pyqtSignal(int)
stop = False
pause = False
def get_sin_out(self,msg):
if msg == 1:
self.stop = True
elif msg == 2:
self.pause = True
elif msg == 0:
self.stop = False
self.pause = False
def Speak(self,text):
if text == None:
text = "message is null"
engine = pyttsx3.init()
engine.setProperty('rate', 150)
engine.setProperty('volume', 2)
voices = engine.getProperty('voices')
try:
engine.setProperty('voice',voices[2].id)
except Exception as e:
print("获取声音引擎失败")
return
for word in text:
self.code.connect(self.get_sin_out)
if self.stop :
print("中止朗读")
break
elif self.pause:
while self.pause:
pass
engine.say(word)
engine.runAndWait()
else:
engine.say(word)
engine.runAndWait()
engine.stop()
class MyThread(QThread):
my_str = pyqtSignal(str) # 创建任务信号
speak = pyqtSignal(str)
SpeakMsg = None
myspeak = MySpeak()
def run(self):
"""
多线程功能函数
:return:
"""
self.speak.connect(self.get_sin_out)
if self.SpeakMsg != None:
# Speak(self.SpeakMsg)
self.myspeak.Speak(self.SpeakMsg)
self.my_str.emit("ok")
else:
self.my_str.emit("no") # 发出任务完成信号
def setCode(self,code):
self.myspeak.code.emit(code)
def get_sin_out(self, out_str):
"""
:param out_str:
:return:
"""
self.SpeakMsg = out_str
# print("已接收到signal")
class MyMenu(QSystemTrayIcon):
def __init__(self, MainWindow, parent=None):
super(MyMenu, self).__init__(parent)
self.ui = MainWindow
is_Hide = pyqtSignal(str)
self.Menu()
def Menu(self):
print("menu")
self.menu = QMenu()
self.manage_action = QAction('朗读机', self, triggered=self.manage_clock)
self.quit_action = QAction('退出应用', self, triggered=self.quit_clock)
self.manage_action.setShortcut("Ctrl+6")
# 设置快捷键
self.menu.addAction(self.manage_action)
self.menu.addAction(self.quit_action)
self.setContextMenu(self.menu)
print("设置图标")
Myicon = QtGui.QIcon()
ico_path = os.path.join(os.path.dirname(__file__), "Logo.ico")
Myicon.addPixmap(QtGui.QPixmap(ico_path), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.setIcon(QtGui.QIcon('Logo.ico'))
self.icon = self.MessageIcon()
self.activated.connect(self.app_click)
def manage_clock(self):
self.ui.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.ui.showNormal()
self.ui.activateWindow()
# self.ui.isHide = False
self.ui.center()
def quit_clock(self):
qApp.quit()
def GetHide(self):
print("self.ui.isHide",self.ui.isHide)
return self.ui.isHide
def app_click(self, reason):
isHide = self.GetHide()
print("isHide",isHide)
if isHide:
self.ui.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.ui.showNormal()
self.ui.activateWindow()
# self.ui.isHide = False
self.ui.center()
class UIWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(WINDOW_WEIGHT, WINDOW_HEIGHT)
self.EditorMsg = None
self.moved = False
self.my_thread = MyThread()
self.my_thread.my_str.connect(self.get_sin_out)
self.signal2 = pyqtSignal(str)
self.isHide = False
self.showTitle = False
self.notclick = 0
self.pause = pyqtSignal(int)
self.isPause = False
self.isSpeak = False
self.menu = MyMenu(self)
self.initUI()
def initUI(self):
self.hideTitle()
# widget = QWidget()
# exitAct = QAction(QIcon("/Users/zuozhe/PycharmProjects/Soft-Video/images/m4.png"), "&退出", self)
# exitAct = QAction( "&退出", self)
# self.setWindowFlags(Qt.WindowStaysOnTopHint)#隐藏到托盘
icon = QtGui.QIcon()
ico_path = os.path.join(os.path.dirname(__file__), "Logo.ico")
icon.addPixmap(QtGui.QPixmap(ico_path), QtGui.QIcon.Normal, QtGui.QIcon.On)
self.setWindowIcon(icon)
self.setAcceptDrops(True) #窗体可拖动
self.resize(370, 20)
self.center()
self.setWindowTitle('朗读机')
self.btn_pus = QPushButton("暂停", self)
self.btn1 = QPushButton("开始朗读", self)
self.btn1.move(30, 50)
self.btn_pus.move(10, 50)
# self.btn1.clicked.connect(self.buttonClicked)
# self.btn1.clicked.connect(lambda: self.start_thread())
# self.btn_pus.clicked.connect(lambda:self.BtnPusClick())
self.btn1.clicked.connect(self.start_thread)
self.btn_pus.clicked.connect(self.BtnPusClick)
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.btn1)
hbox.addWidget(self.btn_pus)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.EditorLab()
# self.setupUi()
self.menu.show()
self.show()
def hideTitle(self):
#去掉标题栏
from PyQt5 import Qt
if not self.showTitle:
self.setWindowFlags(Qt.Qt.CustomizeWindowHint)
def getTitleShow(self):
return self.showTitle
def getPusCode(self,code):
if code == 1:
self.isPause = True
def get_sin_out(self, out_str):
"""
:param out_str:
:return:
"""
if out_str == "ok":
self.btn1.setEnabled(True)
self.btn1.setText("开始朗读")
# print("朗读完毕")
elif out_str == "no":
self.start_thread()
def BtnPusClick(self):
print(self.isSpeak)
if not self.isPause :
self.btn_pus.setText("暂停中")
print("已暂停")
self.my_thread.setCode(2)
self.isPause = True
else:
print("取消暂停")
self.btn_pus.setText("暂停")
self.my_thread.setCode(0)
self.isPause = False
def buttonClicked(self):
self.btn1.setEnabled(False)
sender = self.sender()
th = threading.Thread(target = Speak,args=(self.EditorMsg,self))
# Speak()
th.start()
th.join()
time.sleep(1)
def start_thread(self):
"""
启动多线程
:return:
"""
self.btn1.setEnabled(False)
sender = self.sender()
self.btn1.setText("朗读中")
# self.pause.connect(self.get_sin_out)
self.isSpeak = True
try:
print("self.isSpeak",self.isSpeak)
self.my_thread.speak.emit(self.EditorMsg)
self.my_thread.start()
except Exception as e:
print(e)
self.isSpeak = False
def EditorLab(self):
self.lbl = QLabel(self)
self.lbl.setGeometry(QRect(320, 240, 290, 27*4))
self.lbl.setWordWrap(True)
self.lbl.setAlignment(QtCore.Qt.AlignTop)
qle = QLineEdit(self)
qle.setGeometry(QRect(0, 0, 180, 30))
qle.move(30,10)
qle.textChanged[str].connect(self.onChanged)
# self.setMinimumSize(400,400)
def onChanged(self, text):
if self.isSpeak and len(text) == 0:
self.isSpeak = False
# self.my_thread.setCode(1)
self.EditorMsg = text
self.lbl.setText(text)
# self.lbl.setPlainText(text)
self.lbl.adjustSize()
#控制窗口显示在屏幕中心的方法
def center(self):
#获得窗口
qr = self.frameGeometry()
#获得屏幕中心点
cp = QDesktopWidget().availableGeometry().center()
#显示到屏幕中心
qr.moveCenter(cp)
self.move(qr.topLeft())
def Painting(self):
color = random.choice(["CCFFFF","CC6699","CC99FF","99CCFF"])
palette1 = QPalette()
palette1.setColor(self.backgroundRole(),
QColor("#{}".format(color))) # 改变窗体颜色
self.setPalette(palette1)
def enterEvent(self, event):
print("鼠标移入295",self.isHide)
if self.isHide :
self.hide_or_show('show', event)
def leaveEvent(self, event):
if self.isHide :
self.hide_or_show('show', event)
# print("鼠标移出")
# print("leaveEvent")
# self.hide_or_show('hide', event)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
print("鼠标移入307",self.isHide)
if self.isHide :
self.hide_or_show('show', event)
self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
QApplication.postEvent(self, QEvent(174))
event.accept()
self.hide_or_show('show', event)
self.isHide = False
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
try:
self.move(event.globalPos() - self.dragPosition)
event.accept()
except:
pass
def mouseReleaseEvent(self, event):
# 获取鼠标松开的坐标
print("松开鼠标")
qr = self.frameGeometry()
# print(qr.center())
# print("height",qr.height())
# print("width",qr.width())
print("left",qr.left())
print("top",qr.top())
print("right",qr.right())
if not self.isHide:
if qr.top() < 2 :
print("窗体顶部隐藏")
# self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
# tray = TrayIcon(main_)
# tray.show()
# ToastShow("通知","窗体顶部隐藏")
self.isHide = True
elif
qr.left() <2:
print("窗体靠左隐藏")
# ToastShow("通知","窗体靠左隐藏")
self.isHide = True
elif
qr.right() > 1920:
print("窗体靠右隐藏")
# ToastShow("通知","窗体靠右隐藏")
self.isHide = True
if self.isHide:
print("隐藏窗口")
self.menu.GetHide()
self.hide_or_show('hide', event)
else:
print("窗体已隐藏")
def dragMoveEvent(self, event):
print("dragMoveEvent")
def dragLeaveEvent(self, event):
print('dragLeaveEvent...')
def dropEvent(self, event):
print("dropEvent")
def hide_or_show(self, mode, event):
pos = self.frameGeometry().topLeft()
if mode == 'show' and self.moved:
self.isHide = False
self.setWindowFlags( QtCore.Qt.FramelessWindowHint)
if pos.x() + WINDOW_WEIGHT >= SCREEN_WEIGHT: # 右侧显示
self.startAnimation(SCREEN_WEIGHT - WINDOW_WEIGHT + 2, pos.y())
event.accept()
self.moved = False
elif pos.x() <= 0: # 左侧显示
self.startAnimation(0,pos.y())
event.accept()
self.moved = False
elif pos.y() <= 0: # 顶层显示
self.startAnimation(pos.x(),0)
event.accept()
self.moved = False
elif mode == 'hide':
print("隐藏任务栏")
self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint)
if pos.x() + WINDOW_WEIGHT >= SCREEN_WEIGHT: # 右侧隐藏
self.startAnimation(SCREEN_WEIGHT - 2,pos.y())
event.accept()
self.moved = True
elif pos.x() <= 2: # 左侧隐藏
self.startAnimation(2 - WINDOW_WEIGHT,pos.y())
event.accept()
self.moved = True
elif pos.y() <= 2: # 顶层隐藏
self.startAnimation(pos.x(),2 - WINDOW_HEIGHT)
event.accept()
self.moved = True
def startAnimation(self,width,height):
animation = QPropertyAnimation(self,b"geometry",self)
startpos = self.geometry()
animation.setDuration(200)
newpos = QRect(width,height,startpos.width(),startpos.height())
animation.setEndValue(newpos)
animation.start()
def textTovoice(text, name):
try:
engine = pyttsx3.init()
engine.say(test)
# engine.stop()
engine.setProperty('voice', engine.getProperty('voice')[1])
engine.save_to_file(text, "{}.mp3".format(name))
engine.runAndWait()
print("保存声音到文件{}.mp3".format(name))
return None
except Exception as e:
print("转换异常", e)
return e
def Speak(text):
if text == None:
text = "message is null"
engine = pyttsx3.init()
engine.setProperty('rate', 150)
engine.setProperty('volume', 2)
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[2].id)
engine.say(text)
engine.runAndWait()
engine.stop()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = UIWindow()
sys.exit(app.exec_())

目前遇到的问题:先执行start_thread 后 BtnPusClick 方法里面获取到的isSpeak是False(初始化的值),实际上是在start_thread方法里面已经改为True

def BtnPusClick(self):
print(self.isSpeak)
if not self.isPause :
self.btn_pus.setText("暂停中")
print("已暂停")
self.my_thread.setCode(2)
self.isPause = True
else:
print("取消暂停")
self.btn_pus.setText("暂停")
self.my_thread.setCode(0)
self.isPause = False
def start_thread(self):
"""
启动多线程
:return:
"""
self.btn1.setEnabled(False)
sender = self.sender()
self.btn1.setText("朗读中")
# self.pause.connect(self.get_sin_out)
self.isSpeak = True
try:
print("self.isSpeak",self.isSpeak)
self.my_thread.speak.emit(self.EditorMsg)
self.my_thread.start()
except Exception as e:
print(e)
self.isSpeak = False

执行过程

最后

以上就是刻苦口红为你收集整理的【pyqt5 按钮点击事件获取不到参数更新后的值】上代码目前遇到的问题:先执行start_thread 后 BtnPusClick 方法里面获取到的isSpeak是False(初始化的值),实际上是在start_thread方法里面已经改为True的全部内容,希望文章能够帮你解决【pyqt5 按钮点击事件获取不到参数更新后的值】上代码目前遇到的问题:先执行start_thread 后 BtnPusClick 方法里面获取到的isSpeak是False(初始化的值),实际上是在start_thread方法里面已经改为True所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部