使用Tkinter+googletrans开发翻译器遇AttributeError问题求助
解决googletrans库的AttributeError: 'NoneType' object has no attribute 'group'错误
这个错误不是你的代码逻辑问题,而是googletrans官方版本因谷歌翻译API的验证机制更新,无法正确提取请求所需的TKK参数,导致RE_TKK.search(r.text)返回None,调用.group(1)时触发报错。
可行解决方案
1. 安装修复后的googletrans分支版本
卸载现有版本,安装第三方维护的修复版,该版本重新适配了谷歌翻译的token生成逻辑:
pip uninstall googletrans -y pip install googletrans==4.0.0-rc1
2. 修正代码中的细节问题
你的代码还有两处细节需要调整,否则即使库正常也无法正确显示翻译结果:
frame = Frame(root).pack(side=BOTTOM)会导致frame变量为None(pack()返回None),后续组件绑定到frame会失效,需分开初始化和布局change函数返回的是翻译对象,需提取.text属性才能获取翻译后的文本
修正后的完整代码:
from tkinter import * from tkinter import ttk from googletrans import Translator, LANGUAGES def change(text="Type", src="English", dest="Hindi"): trans = Translator() trans1 = trans.translate(text, src=src, dest=dest) return trans1.text # 提取翻译后的文本内容 def data(): s = comb_sor.get() d = comb_dest.get() msg = Sor_txt.get(1.0, END).strip() # 去除末尾换行符,避免空文本请求 if not msg: dest_txt.delete(1.0, END) return textget = change(text=msg, 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='#f1f3f5') lab_txt=Label(root, text="Translator", font=("Inter", 30, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=40, height=50, width=300) # 分开初始化Frame和布局,避免frame为None frame = Frame(root) frame.pack(side=BOTTOM) lab_txt=Label(root, text="Source Text", font=("Inter", 16, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=100, height=30, width=300) Sor_txt = Text(root, font=("Inter", 18, "bold"), bg="#f1f3f5", wrap=WORD) Sor_txt.place(x=10, y=130, height=150, width=480) list_text = list(LANGUAGES.values()) comb_sor = ttk.Combobox(root, value=list_text) comb_sor.place(x=10, y=300, height=40, width=150) comb_sor.set("English") button_change = Button(root, text="Translate", relief=RAISED, command=data) button_change.place(x=170, y=300, height=40, width=150) comb_dest = ttk.Combobox(root, value=list_text) comb_dest.place(x=330, y=300, height=40, width=150) comb_dest.set("English") lab_txt=Label(root, text="Destination Text", font=("Inter", 16, "bold"), bg="#f1f3f5", fg="#495057") lab_txt.place(x=100, y=360, height=30, width=300) dest_txt = Text(root, font=("Inter", 18, "bold"), bg="#f1f3f5", wrap=WORD) dest_txt.place(x=10, y=400, height=150, width=480) root.mainloop()
补充说明
- 若遇到网络问题,可给Translator设置代理:
trans = Translator(proxies={'http': 'http://proxy_ip:port', 'https': 'https://proxy_ip:port'}) - 长期使用建议考虑谷歌官方翻译API(需付费,稳定性有保障)或其他开源翻译接口。
内容的提问来源于stack exchange,提问作者Tanvi
相关产品推荐
相关产品推荐

