首页 > 解决方案 > 当 pyttsx3 开始运行时,tkinter GUI 冻结

问题描述

我最近开始学习 pyttsx3 ,您可以在其中将文本转换为语音。我面临一个问题,一旦 pyttsx3 开始说话,我的整个 GUI 就会冻结,直到 pyttsx3 停止说话。

这是代码:

from tkinter import *
import pyttsx3
root = Tk()

def read():
    engine.say(text.get(1.0 , END))
    engine.runAndWait()

engine = pyttsx3.init()

text = Text(width = 65 , height = 20 , font = "consolas 14")
text.pack()

text.insert(END , "This is a text widget\n"*10)

read_button = Button(root , text = "Read aloud" , command = read)
read_button.pack(pady = 20)

mainloop()

在这里,当我单击大声朗读按钮时,整个 GUI 冻结,我无法对其进行任何操作,直到 pyttsx3 停止说话。

有没有办法解决这个问题?

如果有人可以帮助我,那就太好了。

标签: pythontkinter

解决方案


使用线程执行read()

import threading

...

read_button = Button(root, text="Read aloud", command=lambda: threading.Thread(target=read, daemon=True).start())
...

推荐阅读