from tkinter import *
import urllib.request
import urllib.parse
import json
class My_GUI():
def __init__(self,top):
self.top = top
def set_top(self):
#标题设置
self.top.title('爬虫翻译_V2.0')
self.top.geometry('600x400+10+10')
#标签设置
self.data_Label = Label(self.top,text='请输入需要翻译的内容:(点击对应按钮进行翻译)')
self.data_Label.grid(row=0,column=0)
self.text_Label = Label(self.top,text='以下为翻译结果:')
self.text_Label.grid(row=5,column=0,rowspan=3)
#文本框设置
self.data_Text = Text(self.top,width=85, height=10)
self.data_Text.grid(row=1,column=0,rowspan=4,columnspan=10)
self.text_Text = Text(self.top,width=85, height=10)
self.text_Text.grid(row=8,column=0,rowspan=4,columnspan=10)
#按钮设置
self.fy_Button = Button(self.top,text='翻译为中文',activebackground='blue',command = self.run_CN)
self.fy_Button.grid(row=5,column=1)
self.fy_Button = Button(self.top,text='翻译为英文',activebackground='red',command = self.run_EN)
self.fy_Button.grid(row=5,column=2)
#运算代码
def run_CN(self) :
targetL = 'zh-CN'
self.FY(targetL)
def run_EN(self) :
targetL = 'en'
self.FY(targetL)
def FY(self,targetL):
self.text_Text.delete(1.0,'end')
url = 'http://fanyi.pdf365.cn/v2/api/getTranslateResult'
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0'}
data = {}
data['orginL'] = "auto"
data['targetL'] = targetL
data['text'] = urllib.parse.quote(self.data_Text.get('1.0','end'))
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=data, headers=head)
html = urllib.request.urlopen(req)
html = html.read().decode('utf-8')
target = json.loads(html)
self.text_Text.insert('end',target['result'])
def gui_start():
top = Tk()
Windows = My_GUI(top)
Windows.set_top()
top.mainloop()
gui_start()
你参考下我以前的代码吧,这代码还有好多可以优化的; |