python实现翻译小工具
pycharm编辑器下的代码
from tkinter import messagebox
import json
from tkinter import *
import requests
def fanyi():
#拿到第一个输入框里面的内容
#strip能去掉空格,不翻译
content = entry1.get().strip()
url = “http://fanyi.youdao.com/translate” #有道翻译的API接口
data = {
‘i’: content,
‘doctype’: ‘json’
}
r = requests.post(url, data=data)
ret = r.content.decode()
#拿到翻译出来的结果
result = json.loads(ret)
rep = result[‘translateResult’][0][0][‘tgt’]
res.set(rep)
master = Tk() #实例化对象
master.geometry(‘400x100+450+280’)
Label1 = Label(master, text=‘输入内容’, fg=‘red’, font=(‘gb2312’, 18))
Label1.grid(row=0, column=0)
Label2 = Label(master, text=‘结果’, fg=‘red’, font=(‘gb2312’, 18))
Label2.grid(row=1, column=0)
entry1 = Entry(master, fg=‘red’, font=(‘gb2312’, 18))
entry1.grid(row=0, column=1)
res = StringVar()
entry2 = Entry(master, fg=‘red’, font=(‘gb2312’, 18), textvariable=res)
entry2.grid(row=1, column=1)
button1 = Button(master, text=‘翻译’, fg=‘red’, font=(‘gb2312’, 18), command=fanyi)
button1.grid(row=2, column=0)
button2 = Button(master, text=‘退出’, fg=‘red’, font=(‘gb2312’, 18), command=master.quit)
button2.grid(row=2, column=1)
master.mainloop()
-----------------------------------------------------------------仅供记录