0

I have recently started programming and written a fairly simple program. But stuck at a point. My program does a very simple thing that when you click a button it will say a line and shows that text on the screen. But it is speaking the text first and then displays it on the screen but I want its reverse, i.e it should first display it on the screen and then speak the text.

    from tkinter import *
    import pyttsx3

    root = Tk()

    def speak():
        engine = pyttsx3.init()
        say = "I am speaking."

        text.insert("0.0", say)

        engine.say(say)
        engine.runAndWait()

    text = Text(root)
    text.pack()
    btn = Button(root, text="speak", command=speak)
    btn.pack()

    root.mainloop()

Thanks in advance.

4

2 回答 2

1

It is because engine.runAndWait() blocks the application, and so text box cannot be updated by tkinter mainloop until the speaking completed.

You can call text.update_idletasks() to force tkinter to update the text box before the speaking:

    engine = pyttsx3.init() # initialize only once

    def speak():
        say = "I am speaking."
        text.insert("0.0", say)
        text.update_idletasks() # force tkinter update

        engine.say(say)
        engine.runAndWait()
于 2020-12-11T08:39:49.853 回答
0

You could delay the call to engine.say

from tkinter import *
import pyttsx3


def speak(sentence):
    engine.say(sentence)
    engine.runAndWait()        


def display_and_speak():
    sentence = "I am speaking."
    text.insert("1.0", sentence)
    root.after(1000, speak, sentence)   # call to speak delayed 1 second


engine = pyttsx3.init()

root = Tk()
text = Text(root)
text.pack()
btn = Button(root, text="speak", command=display_and_speak)
btn.pack()

root.mainloop()
于 2020-12-10T14:41:52.380 回答