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

如何解决多语言文本转语音工具中的Tkinter回调异常?

解决Googletrans库的AttributeError异常(Tkinter多语言翻译工具)

问题原因

你遇到的AttributeError: 'NoneType' object has no attribute 'group',是因为官方googletrans库长期未维护,其token获取逻辑与Google翻译当前的API不兼容,导致无法正常生成请求令牌。

解决方法

1. 安装兼容版本的googletrans

卸载现有失效版本,安装第三方维护的候选版本:

pip uninstall googletrans
pip install googletrans==4.0.0-rc1

该版本修复了令牌生成逻辑,能正常调用Google翻译接口。

2. 代码优化(可选但推荐)

  • 全局初始化翻译器实例,避免每次点击按钮重复创建,提升性能
  • 获取输入文本时去除末尾换行符,避免翻译空内容的无效请求

修改后的完整代码

from tkinter import *
from tkinter import ttk
from googletrans import Translator,LANGUAGES

# 全局初始化翻译器,避免重复创建实例
trans = Translator()

def change(text="type",src="English",dest="Hindi"):
    trans1 = trans.translate(text, src=src, dest=dest)
    return trans1.text

def data():
    s = comb_sor.get()
    d = comb_dest.get()
    # 去除文本末尾的换行符,避免空内容请求
    masg = Sor_txt.get(1.0, END).strip()
    
    # 处理空输入情况
    if not masg:
        dest_txt.delete(1.0, END)
        dest_txt.insert(END, "请输入要翻译的文本")
        return
    
    textget = change(text=masg, src=s, dest=d)
    dest_txt.delete(1.0, END)
    dest_txt.insert(END, textget)

root = Tk()
root.title("Translator")
root.geometry("500x700")
root.config(bg='Red')

lab_txt=Label(root,text="Translator",font=("Time New Roman",40,"bold"))
lab_txt.place(x=100,y=40,height=50,width=300)

frame=Frame(root).pack(side=BOTTOM)

lab_txt=Label(root,text="Source Text",font=("Time New Roman",20,"bold"),fg="Black",bg="red")
lab_txt.place(x=100,y=100,height=20,width=300)

Sor_txt=Text(frame,font=("Time New Roman",20,"bold"),wrap=WORD)
Sor_txt.place(x=10,y=130,height=150,width=480)

list_text=list(LANGUAGES.values())

comb_sor=ttk.Combobox(frame,value=list_text)
comb_sor.place(x=10,y=300,height=40,width=150)
comb_sor.set("english")

button_change=Button(frame,text="Translate",relief=RAISED,command=data)
button_change.place(x=170,y=300,height=40,width=150)

comb_dest=ttk.Combobox(frame,value=list_text)
comb_dest.place(x=330,y=300,height=40,width=150)
comb_dest.set("english")

lab_txt=Label(root,text="Dest Text",font=("Time New Roman",20,"bold"),fg="Black",bg="red")
lab_txt.place(x=100,y=360,height=20,width=300)

dest_txt=Text(frame,font=("Time New Roman",20,"bold"),wrap=WORD)
dest_txt.place(x=10,y=400,height=150,width=480)

root.mainloop()

内容的提问来源于stack exchange,提问作者Indibar Dutta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:40:43