import tkinter as tk
import requests
import urllib.request
import urllib.parse
import re
import json
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
#1
self.lblTitle = tk.Label(self, text="请输入你想要翻译文字:")
self.lblTitle.grid(row=0, column=0 )
self.editText = tk.Text(self, width=40, height=12)
self.editText.grid(row=1, column=0)
#按钮
self.btnOk = tk.Button(self, text='翻译',command=self.youdaoTranslte)
self.btnOk.grid(row=0, column=0, columnspan=8)
# root.bind('', self.youdaoTranslte) #失败 OvO, 增加快捷键失败
#2还可以添加对已存在窗口的翻译结果删除,再添加新的翻译结果的功能
self.lblresul = tk.Label(self, text="翻译的结果:")
self.lblresul.grid(row=0, column=1)
self.resultText = tk.Text(self, width=40, height=12)
self.resultText.grid(row=1, column=1)
#root.bind('', self.youdaoTranslte)
def youdaoTranslte(self, event=None):
Request_URL = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
Form_Data = {}
Form_Data['doctype'] = 'json' #can't delete,return type
Form_Data['i'] = self.editText.get(0.0, tk.END) #print(Form_Data['i'])
data = urllib.parse.urlencode(Form_Data).encode('utf-8')
response = urllib.request.urlopen(Request_URL,data)
html = response.read().decode('utf-8')
translate_results = json.loads(html)
translate_results = translate_results['translateResult'][0][0]['tgt']
#print("the translate result is:%s" % translate_results)
self.resultText.insert(tk.END, translate_results)
root = tk.Tk()
root.title('简易翻译器')
root.geometry("580x200+350+140")
app = Application(master=root)
app.mainloop()
运行结果显示: