首页 > 解决方案 > 从导入模块中的函数更改字符串变量

问题描述

我正在制作一个 python Tkinter GUI,它将实时将麦克风中的音频转录为文本,同时,如果说出并检测到“哦,不”或“erm”这个词,则会在屏幕上显示一条警告消息。我将语音识别脚本transcribe.py作为一个模块导入到主程序sample.py中。sample.py我的问题是:当在导入的模块中检测到单词“erm”时,如何更改主程序中 tk.Label 的文本transcribe.py

下面是我的代码。

#sample.py(class of the window that the warning message should be shown on)

import transcribe.py

class PracticePage(tk.Frame, App):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        tk.Frame.config(self, bg="white")

        global label_var 
        label_var = tk.StringVar()
        label_var.set("")
        self.timeLeft = tk.Label(self, textvariable= label_var, font ="遊ゴジックLight 20", bg ="white")

        self.timeLeft.place(relwidth = 0.4, relheight = 0.1, relx = 0.5, rely = 0.45, anchor = "center")

这是我的语音识别模块中代码的一部分。

#transcribe.py
def listen_print_loop(responses): #responses is the audio stream from microphone
spoken = []

for response in responses:
    if not response.results:
        continue

    result = response.results[0]
    if not result.alternatives:
        continue

    transcript = result.alternatives[0].transcript
    overwrite_chars = ' ' * (num_chars_printed - len(transcript))

    spoken.append(transcript + overwrite_chars)

    if "erm" in spoken:
        #change the text of label in sample.py here

    if not result.is_final:
        num_chars_printed = len(transcript)

    else:
        spoken.append(transcript + overwrite_chars)
        final_spoken = ''.join(spoken) 
        print(final_spoken)

我是 python 初学者,如果我的问题令人困惑,我很抱歉。如果您有任何不明白的地方,请进一步问我。谢谢你。

标签: pythontkinterglobal-variablesspeech-recognition

解决方案


推荐阅读