from tkinter import *
from tkinter import messagebox
import requests
'''搭建页面'''
# 1 获取用户输入的词汇
# 2 爬取有道翻译结果 反爬。
# 3 根据获取到的结果显示到窗口上
def translation():
'''完成翻译'''
content = entry.get()
content = content.strip()#去除空格。split():分割
if content == '':
messagebox.showinfo("提示",message='请输入要翻译的内容')
else:
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=true'
data ={}
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_CLICKBUTTON'
data['typeResult'] = 'false'
resu = requests.post(url,data=data)
result = resu.json()
tran = result['translateResult'][0][0]['tgt']
# 设置显示到窗口上面的输入框内
res.set(tran)
return res
#创建窗口
window = Tk()
#尺寸
window.geometry('550x200+700+400')
#标题
window.title('小虎翻译')
#控件
label = Label(window,text='要翻译的内容:',font=('宋体',12),fg='red')
#位置 pack place 网格
label.grid(row=0,column=0)
label1 = Label(window,text='翻译后的内容:',font=('宋体',12),fg='green')
label1.grid(row=1,column=0)
#输入框
entry = Entry(window,width=440,font=('微软雅黑',15))
entry.grid(row=0,column=1)
#创建一个字符串变量对象。用来存储翻译之后的结果。
res = StringVar()
entry1 = Entry(window,width=440,font=('微软雅黑',15),textvariable=res)
entry1.grid(row=1,column=1)
#按钮
button = Button(window,text='翻译',width=10,command=translation)
button.grid(row=2,column=0,sticky=W)
button1 = Button(window,text='退出',width=10,command=window.quit)
#button1.grid(row=2,column=1,sticky=E)
button1.place(x=460,y=70)
#显示窗口
window.mainloop()
网友评论