防止pyttsx3冻结GUI

3
我已经建立了一个基于Kivy的GUI,与使用pyttsx3进行语音输出协作。但是,当我运行pyttsx3时会阻塞主线程,从而导致GUI冻结。
如何在另一个线程上运行pyttsx3,使输出可以在主线程中被听到,或者有没有一种方法可以在不阻塞主线程的情况下运行pyttsx3,并防止它冻结我的Kivy GUI?
这是一个示例代码,当您单击按钮时,应该打印文本框中的文本,但是在运行pyttsx3时会导致GUI冻结:
import pyttsx3
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.app import App



engine = pyttsx3.init()

engine.setProperty('rate', 150)
engine.setProperty('volume', 1)

class example(App):

    def build(self):

        layout = FloatLayout()

        self.textbox = TextInput(text="", multiline=False, font_size=12, size_hint_y=None, size_hint_x=None, width = 150, height = 30, pos_hint= {"x":0.4, "y":0.8})



        self.btnText = Button(text="Print text", font_size=12, size_hint_y=None, size_hint_x=None, width = 150, height = 30, pos_hint= {"x":0.4, "y":0.6})
        self.btnText.bind(on_press=self.print)


        layout.add_widget(self.textbox)
        layout.add_widget(self.btnText)

        return layout

    def print(self, instance):
        engine.say("this is an example of kivy being blocked my pyttsx3")
        engine.runAndWait()
        print(self.textbox.text)



if __name__ == '__main__':
    example().run()

我尝试以下操作:
thread2 = threading.Thread(target=engine.say, args = ("some text here",))
thread2 = threading.Thread(target=engine.runAndWait(),)
thread2.start()
thread2.join()

但是上述代码仍然会阻塞线程并导致Kivy GUI冻结。
1个回答

4

正如他所指出的,您需要在一个线程中运行它:

import threading

# ...

class example(App):
    # ...

    def print(self, instance):
        threading.Thread(
            target=self.run_pyttsx3, args=(self.textbox.text,), daemon=True
        ).start()

    def run_pyttsx3(self, text):
        engine.say(text)
        engine.runAndWait()

# ...

非常感谢@eyllanesc,我在使用kivy.Image()加载图像时遇到了类似的问题,当我在另一个线程上运行数据时,应用程序中不会显示数据。 - BrigaDella
是的,我看到了他的帖子,我尝试着实现了,但失败了 @eyllanesc。 - BrigaDella

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接