urllib是Python标准库中最常用的python网页访问模块,它可以让用户像访问文本一样读取网页的内容
```
from tkinter import *
from urllib import request
from urllib import parse
import json
import hashlib
def translate_Word(en_str):
URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
Form_Data = {} #创建From_Data字典,存储向服务器发送的Data
Form_Data['from'] = 'en' #译前---英文
Form_Data['to'] = 'zh' #译后---中文
Form_Data['q'] = en_str
Form_Data['appid'] = '2015063000000001' #自己申请的app id
Form_Data['salt'] = '1435660288'
Key = "12345678" #平台分配的密钥
m = Form_Data['appid'] + en_str + Form_Data['salt'] + Key
m_MD5 = hashlib.md5(m.encode('utf8'))
Form_Data['sign'] = m_MD5.hexdigest()
data = parse.urlencode(Form_Data).encode('utf-8') #使用urlencode()方法转换为标准格式
response = request.urlopen(URL,data)
html = response.read().decode('utf-8') #读取信息并解码
translate_results = json.loads(html)
print(translate_results)
translate_results = translate_results['trans_result'][0]['dst'] #找到翻译结果
print("翻译的结果是:%s" % translate_results)
return translate_results
def leftClick(event):
en_str = Entry1.get()
print(en_str)
vText = translate_Word(en_str)
Entry2.config(Entry2,text = vText)
s.set("")
Entry2.insert(0,vText)
def leftClick2(event):
s.set("")
Entry2.insert(0,"")
if __name__ == "__main__":
root = Tk()
root.title("单词翻译器")
root['width'] = 250;root['height'] = 130
Label(root,text = '输入要翻译的内容:',width = 15).place(x = 1,y = 1) #绝对坐标
Entry1 = Entry(root,width = 20)
Entry1.place(x = 110,y = 1)
Label(root,text = '翻译的结果:',width = 18).place(x = 1,y = 20)
s = StringVar()
s.set("大家好,这是测试")
Entry2 = Entry(root,width = 20,textvariable = s)
Entry2.place(x = 110,y = 20)
Button1 = Button(root,text = '翻译',width = 8)
Button1.place(x = 40,y = 80)
Button2 = Button(root,text = '清空',width = 8)
Button2.place(x = 110,y = 80)
Button1.bind("
Button2.bind("
root.mainloop()
```