Search code examples
python-3.xtkinterpyttsx3

Changing order of execution in python


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.


Solution

  • 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()