import requests
import json
from tkinter import Tk,Button,Entry,Label,Text,END
class YouDaoFanyi(object):
def __init__(self):
pass
def crawl(self,word):
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
#使用post需要一個鏈接
data={'i': word,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTIME',
'typoResult': 'false'}
#將需要post的內容,以字典的形式記錄在data內。
r = requests.post(url, data)
#post需要輸入兩個參數,一個是剛才的鏈接,一個是data,返回的是一個Response對象
answer=json.loads(r.text)
#你可以自己嘗試print一下r.text的內容,然后再閱讀下面的代碼。
result = answer['translateResult'][0][0]['tgt']
return result
class Application(object):
def __init__(self):
self.window = Tk()
self.fanyi = YouDaoFanyi()
self.window.title(u'我的翻譯')
#設置窗口大小和位置
self.window.geometry('310x370+500+300')
self.window.minsize(310,370)
self.window.maxsize(310,370)
#創建一個文本框
#self.entry = Entry(self.window)
#self.entry.place(x=10,y=10,width=200,height=25)
#self.entry.bind("
",self.submit1)
self.result_text1 = Text(self.window,background = 'azure')
# 喜歡什么背景色就在這里面找哦,但是有色差,得多試試:http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
self.result_text1.place(x = 10,y = 5,width = 285,height = 155)
self.result_text1.bind("
",self.submit1)
#創建一個按鈕
#為按鈕添加事件
self.submit_btn = Button(self.window,text=u'翻譯',command=self.submit)
self.submit_btn.place(x=205,y=165,width=35,height=25)
self.submit_btn2 = Button(self.window,text=u'清空',command = self.clean)
self.submit_btn2.place(x=250,y=165,width=35,height=25)
#翻譯結果標題
self.title_label = Label(self.window,text=u'翻譯結果:')
self.title_label.place(x=10,y=165)
#翻譯結果
self.result_text = Text(self.window,background = 'light cyan')
self.result_text.place(x = 10,y = 190,width = 285,height = 165)
#回車翻譯
def submit1(self,event):
#從輸入框獲取用戶輸入的值
content = self.result_text1.get(0.0,END).strip().replace("\n"," ")
#把這個值傳送給服務器進行翻譯
result = self.fanyi.crawl(content)
#將結果顯示在窗口中的文本框中
self.result_text.delete(0.0,END)
self.result_text.insert(END,result)
#print(content)
def submit(self):
#從輸入框獲取用戶輸入的值
content = self.result_text1.get(0.0,END).strip().replace("\n"," ")
#把這個值傳送給服務器進行翻譯
result = self.fanyi.crawl(content)
#將結果顯示在窗口中的文本框中
self.result_text.delete(0.0,END)
self.result_text.insert(END,result)
print(content)
#清空文本域中的內容
def clean(self):
self.result_text1.delete(0.0,END)
self.result_text.delete(0.0,END)
def run(self):
self.window.mainloop()
if __name__=="__main__":
app = Application()
app.run()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
