? 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("<Button-1>",leftClick)
? ? Button2.bind("<Button-1>",leftClick2)
? ? root.mainloop()
```