播放音频时计时器停止更新

Timer stops updating when an audio is played

我已经使用 after() 方法来更新测验的剩余时间,并使用 gtts 模块将问题文本转换为音频,并且使用 playsound 模块播放。但是当播放音频时,计时器停止更新。我该如何解决?

import playsound
import tkinter
import gtts
import os

def speak_que():
    global audio_no
    sound = gtts.gTTS(question_label["text"], lang = "en")
    file_name = "Audio_" + str(audio_no) + ".mp3"
    sound.save(file_name)
    playsound.playsound(file_name)
    os.remove(file_name)
    audio_no += 1

def change_time():
    pre_time = int(time_label["text"])
    if pre_time != 1:
        time_label.config(text = pre_time-1)
        time_label.after(1000, change_time)
    else:
        window.destroy()

window = tkinter.Tk()
audio_no = 0
time_label = tkinter.Label(window, text = "15")
time_label.after(1000, change_time)
question_label = tkinter.Label(window, text = "What is the sum of 4 and 2")
answer = tkinter.Entry(window)
speak = tkinter.Button(window, text = "Speak", command = speak_que)
time_label.pack()
question_label.pack()
answer.pack()
speak.pack()
window.mainloop()

首先,确保您的 speak_que() 例程正在完成,如果没有,您可以安装旧版本的 playsound 1.2.2,因为最新版本往往有问题。

pip uninstall playsound

pip install playsound==1.2.2

接下来,如果您希望计时器在 speak_que() 期间继续(或任何两个并行操作);你必须使用线程,见下文。

import playsound
import tkinter
import gtts
import os
from threading import *

def speak_que():
    global audio_no
    sound = gtts.gTTS(question_label["text"], lang = "en")
    file_name = "Audio_" + str(audio_no) + ".mp3"
    sound.save(file_name)
    playsound.playsound(file_name)
    os.remove(file_name)
    audio_no += 1

def threadedSound():
    t1=Thread(target=speak_que)
    t1.start()

def change_time():
    pre_time = int(time_label["text"])
    if pre_time != 1:
        time_label.config(text = pre_time-1)
        time_label.after(1000, change_time)
    else:
        window.destroy()

window = tkinter.Tk()
audio_no = 0
time_label = tkinter.Label(window, text = "15")
time_label.after(1000, change_time)
question_label = tkinter.Label(window, text = "What is the sum of 4 and 2")
answer = tkinter.Entry(window)
speak = tkinter.Button(window, text = "Speak", command = threadedSound)
time_label.pack()
question_label.pack()
answer.pack()
speak.pack()
window.mainloop()