之前根据别人写的翻译软件,发现别人写的有bug,下面自己重新写了下,站在巨人的肩膀上写的,废话不多说,直接上代码:
#coding:utf-8
import tkinter as tk
from tkinter import messagebox
import requests
from tkinter import *
root = tk.Tk()
# 第2步,给窗口的可视化起名字
root.title('翻译软件')
# 窗口大小
root.geometry('370x100')
s_width = root.winfo_screenwidth()
s_height = root.winfo_screenheight()
print s_height,s_width
l_x = round((s_width-500)/2)
l_y = round((s_height-300)/2)
size_xy = '%dx%d+%d+%d' % (500, 300, l_x, l_y)
root.geometry(size_xy)
#输入翻译内容
lable = tk.Label(root, text='请输入内容:')
lable.grid()
extry= tk.Entry(root, font=('微软雅黑',15))
extry.grid(row=0, column=1)
res = StringVar()
#翻译结果展示页面
lable1 = tk.Label(root, text='翻译内容:')
lable1.grid()
extry1= tk.Entry(root, font=('微软雅黑',15), textvariable = res)
extry1.grid(row=1,column=1)
def translate():
transContent = extry.get()
transContent = transContent.strip()
if transContent=='':
messagebox.showinfo("不能为空")
else:
url ="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
}
data = {
"i":transContent,
"from":"AUTO",
"to":"AUTO",
"smartresult":"dict",
"client":"fanyideskweb",
"salt":"15648112903464",
"sign":"1da5b0329954ef7c9ce772ef17ef6549",
"ts":"1564811290346",
"bv":"53539dde41bde18f4a71bb075fcf2e66",
"doctype":"json",
"version":"2.1",
"keyfrom":"fanyi.web",
"action":"FY_BY_REALTlME"
}
resUrl = requests.post(url, data, headers=headers)
resContent = resUrl.json()
resTrans = resContent["translateResult"][0][0]["tgt"]
# print resTrans
res.set(resTrans)
#点击翻译触发事件
transButton = Button(root, width=10, text='翻译', command=translate)
transButton.grid(row=2, column=0, sticky = W)
#点击退出
transButton = Button(root, width=10, text='退出', command=root.quit)
transButton.grid(row=2, column=1, sticky = E)
root.mainloop()
结果展示: