from tkinter import *
from tkinter import messagebox
import requests
def translation():
# 获取用户输入的单词
content = entry.get()
print(content)
if content == "":
# 提示框
messagebox.showinfo("提示", "请输入要翻译的单词")
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
header = {
"User-Agent": "Mozilla/5.0(Macintosh;U;IntelMacOSX10_6_8;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50"
}
data = {}
data["i"] = content
data["action"] = "FY_BY_REALTIME"
# 加密关键词fanyideskweb
data["client"] = "fanyideskweb"
data["doctype"] = "json"
data["from"] = "AUTO"
data["keyfrom"] = "fanyi.web"
# <script type="text/javascript" src="http://shared.ydstatic.com/fanyi/newweb/v1.0.9/scripts/newweb/fanyi.min.js"></script>
# i = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10)),
# o = n.md5("fanyideskweb" + t + i + "ebSeFb%=XZ%T[KZ)c(sy!");
# 时间戳
# data['salt'] = '1527917223195'
# 签名, 经过加密的
# data['sign'] = '31236d70720771c58b2fe5a7b78d51bb'
data["smartresult"] = "dict"
data["to"] = "AUTO"
data["typoResult"] = "false"
data["version"] = "2.1"
result = requests.post(url, data=data, headers=header)
print(result)
translation = result.json()
print(translation)
translation = translation["translateResult"][0][0]["tgt"]
print(translation)
res.set(translation)
# 以下为桌面小程序代码
# 创建窗口
root = Tk()
# 窗口标题Title
root.title("阿谋翻译")
# # 窗口大小
# root.geometry('380x100')
#
# # 窗口位置
# root.geometry('+500+300')
# 窗口大小与窗口位置
root.geometry("360x100+500+300")
# 标签控件
lable = Label(root, text="翻译内容:", font=("楷体"), fg="green")
lable.grid(row=0, column=0)
lable1 = Label(root, text="翻译结果:", font=("楷体"), fg="red")
lable1.grid(row=1, column=0)
# 变量
res = StringVar()
# 输入控件
entry = Entry(root, font=("微软雅黑", 15))
entry.grid(row=0, column=1)
entry1 = Entry(root, textvariable=res, font=("微软雅黑", 15))
entry1.grid(row=1, column=1)
# 按钮控件
button = Button(root, text="翻译", width=10, font=("微软雅黑", 10), command=translation)
# sticky 对齐方式 NSEW 上下左右
button.grid(row=2, column=0, sticky=W)
button1 = Button(root, text="退出", width=10, font=("微软雅黑", 10), command=root.quit)
# sticky 对齐方式 NSEW 上下左右
button1.grid(row=2, column=1, sticky=E)
# 消息循环, 显示窗口
root.mainloop()