python之作一個簡易的翻譯器(一)

平時常常在網上翻譯一些單詞,突發奇想,可不能夠直接調某些免費翻譯網站的接口呢?而後作一個圖形界面的翻譯小工具?下面開始實踐編程

1.先找一下有哪些免費翻譯的接口

百度了一下關鍵字「免費翻譯接口」,而後找到一篇帖子,是介紹有哪些免費翻譯接口的,上面有谷歌翻譯、百度翻譯、有道翻譯、必應翻譯等等,最終選擇了有道翻譯json

2.使用requests庫請求

代碼構造以下函數

# -*- coding:utf-8 -*-
import requests

string = str(input("請輸入一段要翻譯的文字:"))
data = {
'doctype': 'json',
'type': 'AUTO',
'i':string
}
url = "http://fanyi.youdao.com/translate"
r = requests.get(url,params=data)
result = r.json()
print(result)

運行結果以下工具

能夠看到「tgt」就是翻譯結果,提取翻譯結果,以下oop

translate_result = result['translateResult'][0][0]["tgt"]
print(translate_result)

3.利用tkinter作一個GUI界面程序

 

# -*- coding:utf-8 -*-

import requests
from requests.exceptions import RequestException
import tkinter as tk
class Translate():
    def __init__(self):
        self.window = tk.Tk()  #建立window窗口
        self.window.title("簡易翻譯器")  # 定義窗口名稱
        self.window.resizable(0,0)  # 禁止調整窗口大小
        self.input = tk.Entry(self.window, width=80)  # 建立一個輸入框,並設置尺寸
        self.info = tk.Text(self.window, height=18)   # 建立一個文本展現框,並設置尺寸
        # 添加一個按鈕,用於觸發翻譯功能
        self.t_button = tk.Button(self.window, text='翻譯', relief=tk.RAISED, width=8, height=1, command=self.fanyi)
        # 添加一個按鈕,用於觸發清空輸入框功能
        self.c_button1 = tk.Button(self.window, text='清空輸入', relief=tk.RAISED, width=8, height=1, command=self.cle_e)
        # 添加一個按鈕,用於觸發清空輸出框功能
        self.c_button2 = tk.Button(self.window, text='清空輸出', relief=tk.RAISED,width=8, height=1, command=self.cle)
        # 添加一張圖標
        self.image_file = tk.PhotoImage(file='py128.png')
        self.label_image = tk.Label(self.window, image=self.image_file)

    def gui_arrang(self):
        """完成頁面元素佈局,設置各部件的位置"""
        self.input.grid(row=0,sticky="W",padx=1)
        self.info.grid(row=1)
        self.t_button.grid(row=0,column=1,padx=2)
        self.c_button1.grid(row=0, column=2, padx=2)
        self.c_button2.grid(row=0,column=3,padx=2)
        self.label_image.grid(row=1, column=1,columnspan=3)

    def fanyi(self):
        """定義一個函數,完成翻譯功能"""
        original_str = self.input.get()  # 定義一個變量,用來接收輸入框輸入的值
        data = {
            'doctype': 'json',
            'type': 'AUTO',
            'i': original_str  # 將輸入框輸入的值,賦給接口參數
        }
        url = "http://fanyi.youdao.com/translate"
        try:
            r = requests.get(url, params=data)
            if r.status_code == 200:
                result = r.json()
                translate_result = result['translateResult'][0][0]["tgt"]
                self.info.delete(1.0, "end")  # 輸出翻譯內容前,先清空輸出框的內容
                self.info.insert('end',translate_result)  # 將翻譯結果添加到輸出框中
        except RequestException:
            self.info.insert('end', "發生錯誤")
    def cle(self):
        """定義一個函數,用於清空輸出框的內容"""
        self.info.delete(1.0,"end")  # 從第一行清除到最後一行

    def cle_e(self):
        """定義一個函數,用於清空輸入框的內容"""
        self.input.delete(0,"end")

def main():
    t = Translate()
    t.gui_arrang()
    tk.mainloop()

if __name__ == '__main__':
    main()

效果以下佈局

 

關於GUI編程參考:https://www.jianshu.com/p/8abcf73adba3網站

相關文章
相關標籤/搜索