You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数执行过程中实时更新Label控件的问题求助

Python函数执行过程中实时更新Label控件的问题求助

大家好,我现在碰到个头疼的问题:我想在submit函数运行的全程实时更新Label的内容,但奇怪的是,Label上的文字总是要等整个函数完全执行结束后才会显示出来。我已经试了好几种更新Label的方法,可还是没搞定,有没有朋友能帮我分析分析呀?

我尝试过的Label更新方式:

  • 使用label.configure(text=chars)修改文本内容
  • 先调用label.pack_forget(),再设置label["text"]="2. Yay!! I am updated"重新显示

下面是我的代码(注:这段代码是我从其他网站复制来练习用的):

import tkinter as root
from tkinter import ttk
import speech_recognition as sr
from gtts import gTTS
from playsound import playsound
import os

# 假设lang_list_voice和trans_text是已定义的变量/函数
lang_list_voice = ["hindi", "hi", "english", "en"]
def trans_text(to_lang_tran, text_for_tran):
    # 模拟翻译逻辑
    return f"Translated to {to_lang_tran}: {text_for_tran}"

class VoiceTrans(root.Frame):
    def __init__(self, parent, controller):
        self.var_char = None
        self.text_var = root.StringVar()
        self.lang_var = root.StringVar()
        root.Frame.__init__(self, parent)
        
        self.label = root.Label(self, text="His Windows Use Audio For Translate ")
        self.label.pack(padx=10, pady=10)
        
        self.lang_label = root.Label(self, text='Voice Translation', font=('calibre', 10, 'bold'))
        self.lang_label.pack(padx=1, pady=1)
        
        new_windows = ttk.Button(self, text='  START  ', command=self.submit)
        new_windows.place(x=165, y=255)
        
        self.switch_window_button = ttk.Button(
            self, text="Return to menu", command=lambda: controller.show_frame(MainPage)
        )
        self.switch_window_button.pack(side="bottom", fill=root.X)
        
        # 关闭窗口的按钮
        self.switch_window_button = ttk.Button(
            self, text="Quit", command=lambda: controller.destroy_root()
        )
        self.switch_window_button.pack(side="bottom", fill=root.X)

    def set_label(self, chars):
        var_char = ttk.Label(self, foreground='red')
        var_char.pack(padx=0, pady=1)
        var_char.configure(text=chars)

    def submit(self):
        flag = 0
        # 捕获语音
        def take_command():
            r = sr.Recognizer()
            with sr.Microphone() as source:
                self.set_label("listening.....")
                print("listening.....")
                r.pause_threshold = 1
                audio = r.listen(source)
                
                try:
                    print("Recognizing.....")
                    query = r.recognize_google(audio, language='en-in')
                    self.user_label = ttk.Label(self, text=f"The User said {query}\n", font=('calibre', 10,))
                    self.user_label.pack(padx=140, pady=195)
                    print(f"The User said {query}\n")
                except Exception as e:
                    again_voice = ttk.Label(self, foreground='red')
                    again_voice.pack(padx=0, pady=1)
                    again_voice['text'] = "say that again please....."
                    print("say that again please.....")
                    return "None"
            return query
        
        # 获取用户输入
        query = take_command()
        while query == "None":
            query = take_command()

        def destination_language():
            chose_lang = ttk.Label(self, foreground='red')
            chose_lang.pack(padx=0, pady=1)
            chose_lang['text'] = "What language would you like to translate to?"
            print("Enter the language in which you want to convert : Ex. Hindi , English , etc.")
            print()
            
            to_lang = take_command()
            while to_lang == "None":
                to_lang = take_command()
            to_lang = to_lang.lower()
            return to_lang
        
        to_lang = destination_language()
        
        # 匹配语言代码
        while to_lang not in lang_list_voice:
            # 先清理之前的错误提示标签
            for widget in self.winfo_children():
                if isinstance(widget, ttk.Label) and widget['foreground'] == 'red':
                    widget.destroy()
            lang = ttk.Label(self, foreground='red')
            lang.pack(padx=0, pady=1)
            lang['text'] = "Wrong input"
            print("Wrong input")
            print()
            to_lang = destination_language()
        
        to_lang = lang_list_voice[lang_list_voice.index(to_lang) + 1]
        
        # 调用翻译函数
        text = trans_text(to_lang_tran=to_lang, text_for_tran=query)
        
        # 播放翻译后的语音
        speak = gTTS(text=text, lang=to_lang, slow=False)
        speak.save("captured_voice.mp3")
        playsound('captured_voice.mp3')
        os.remove('captured_voice.mp3')
        
        # 返回翻译结果
        return text

不管是在take_command里调用set_label,还是直接创建新的Label,所有的文字都要等整个submit函数跑完才会一起显示出来,有没有办法让这些提示文字在函数执行到对应步骤时就实时显示呀?

备注:内容来源于stack exchange,提问作者Shivam Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 09:19:35