如何显示来自终端的程序输出并使用tkinter显示输出?

时间:2019-07-18 15:02:08

标签: python-3.x tkinter raspberry-pi3

可以使用tkinter在GUI窗口中显示语音识别结果的输出吗?

class panggil:
    def __init__(self):
        root = Toplevel()
        root.title("Speaker Recognition(Train)")

        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Speak Anything :")
            audio = r.listen(source)
            try:
                text = r.recognize_google(audio)
                print("You said : {}".format(text))
            except:
                print("Sorry could not recognize your voice")

        root.mainloop()

已执行的程序不显示错误,但不显示任何输出。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以简单地创建一个Text框来显示结果。也最好使用Button来触发识别。下面是一个基于您的代码的简单示例:

from tkinter import *
import speech_recognition as sr

class panggil(Tk):
    def __init__(self):
        super().__init__()
        self.title("Speaker Recognition (Train)")
        self.init_ui()

    def init_ui(self):
        # text box to show message and speech recognition result
        self.output = Text(self, width=40, height=20)
        self.output.pack()
        # button to start the speech recognition
        self.start_btn = Button(self, text="Start", command=self.start_recognize)
        self.start_btn.pack()

    def say(self, msg):
        self.output.insert(END, f"{msg}\n")
        self.output.see(END)
        self.output.update()

    def start_recognize(self):
        self.start_btn.config(state=DISABLED)
        r = sr.Recognizer()
        with sr.Microphone() as source:
            self.say("Speak something ...")
            audio = r.listen(source, timeout=5, phrase_time_limit=2) # better specify timeouts (in case no sound is detected for certain period)
            try:
                text = r.recognize_google(audio)
                self.say(f"You said: {text}")
            except:
                self.say("Sorry could not recognize your voice!")
        self.start_btn.config(state=NORMAL)

panggil().mainloop()