已经写了两篇爬有道翻译的blog了,还想来一篇,因为常听人说,命令行是没有亲和力,反人类的,应用有UI才是好的,所以今天就学习了一下tkinter, 写了个带界面的有道翻译,这回该满意了吧:)

还上个效果图:


再上代码:

#!/user/bin/env python
#-*- coding:utf-8 -*-

from tkinter import *
import tkinter as tk

from urllib import request
from urllib import parse
import json

class YoudaoDict(Frame):
    # 初始化
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        self.entryVar = StringVar()
        self.labelVar = StringVar()
        self.labelVar.set('请输入单词进行翻译')
        self.photo = PhotoImage(file = r'F:\Study\pythonCode\finish\tkinter_study\youdaoDic\youdao.gif')
        self.makeframe()
    
    # Frame内部的部件创建
    def makeframe(self):
        # 输入框,用于输入待翻译的字符串
        entry = Entry(show = None, textvariable = self.entryVar)
        entry.grid(row = 0, column = 0, columnspan = 5, sticky = W, padx = 5, pady = 5)
        # 获取焦点
        entry.focus_set()
        # bind函数,当输入字符串后按Enter建即可翻译
        entry.bind('<Return>', self.translate_bind)
        
        # 用于显示结果
        label = Label(textvariable = self.labelVar).grid(row = 1, rowspan = 3, columnspan = 5, sticky = NW, padx = 5, pady = 5)
        
        # 翻译button
        fanyi_btn = Button(text = '  翻 译  ', command = self.translate)
        fanyi_btn.grid(row = 0, column = 5, padx = 5, pady = 5)
        fanyi_btn.bind("<Return>", self.translate)
        
        # 清空输入框和显示结果栏
        clear_btn = Button(text = '  清 空  ', command = self.clearall).grid(row = 1, column = 5, padx = 5, pady = 5)
        
        # 用于显示youdao logo
        label2 = Label(image = self.photo)
        label2.grid(row = 0, column = 6, rowspan = 3, columnspan = 3, sticky = E+N+W+N, pady = 5)
    
    # bind函数
    def translate_bind(self, event):
        if self.entryVar.get() == '':
            self.labelVar.set('输入框内容为空')
        else:
            value = self.entryVar.get()
            result = self.youdaoTranslate(value)
            self.labelVar.set(value + '\n\n' + result)  
            self.entryVar.set('')
    
    # 事件函数
    def translate(self):
        if self.entryVar.get() == '':
            self.labelVar.set('输入框内容为空')
        else:
            value = self.entryVar.get()
            result = self.youdaoTranslate(value)
            self.labelVar.set(result)
    
    # 清空函数
    def clearall(self):
        self.labelVar.set('')
        self.entryVar.set('')

    # 翻译主函数,就于在网络上爬取翻译结果 
    def youdaoTranslate(self, value):
        # Request URL
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        # user agent
        header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'}
        # 待提交准备Post给url的Data:定义为dict
        form_Data = {}
        form_Data['i'] = value
        form_Data['from'] = 'AUTO'
        form_Data['to'] = 'AUTO'
        form_Data['smartresult'] = 'dict'
        form_Data['client'] = 'fanyideskweb'
        form_Data['doctype'] = 'json'
        form_Data['version'] = '2.1'
        form_Data['keyfrom'] = 'fanyi.web'
        form_Data['action'] = 'FY_BY_REALTIME'
        form_Data['typoResult'] = 'false'
        # 使用urlencode方法转换标准格式 
        data = parse.urlencode(form_Data).encode('utf-8')
        req = request.Request(url, data, headers = header)
        response = request.urlopen(req)
        # html已为json形式
        html = response.read().decode('utf-8')
        # 使用JSON
        translate_result = json.loads(html)
        # print(translate_result)
        # 找到翻译结果
        # 这里推荐一个格式化JSON的好工具:https://c.runoob.com/front-end/53
        translate_result_main = translate_result['translateResult'][0][0]['tgt']
        # 返回翻译结果
        return translate_result_main
            
if __name__ == '__main__':
    root = Tk()
    root.title('有道翻译')
    root.resizable(0,0)
    app = YoudaoDict(root)
    app.grid()
    
    root.mainloop()

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐