tkinter + requests 简单实现翻译软件

 1 from tkinter import *
 2 import requests
 3 import json
 4  
 5 #根据用户输入翻译
 6 def translation():
 7     entry1.delete(0,END)
 8     text = entry.get()
 9     # text = input("请输入要翻译的内容...")
10     url = "http://fanyi.sogou.com/reventondc/translate"
11     data = {'from': 'auto', 'to': 'en', 'client': 'pc', 'fr': 'browser_pc', 'text': text, 'useDetect': 'on',
12             'useDetectResult': 'on', 'needQc': '1', 'uuid': '2d9c20da-29b2-4d2e-ab24-f0f431d38a33', 'oxford': 'on',
13             'isReturnSugg': 'off'}
14     headers = {
15         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
16         'Referer': 'http://fanyi.sogou.com/'}
17     response = requests.post(url, data=data, headers=headers)
18     html_str = response.content.decode()
19     dict_ret = json.loads(html_str)
20     result = dict_ret['translate']['dit']
21     res.set(result)
22  
23  
24 #创建窗口
25 root = Tk()
26  
27 #窗口标题
28 root.title("中英互译")
29  
30 #窗口大小、小写x
31 root.geometry('390x100+500+300')
32  
33 #标签控件
34 lable = Label(root,text = "请输入要翻译的内容:",font = ("微软雅黑"),fg = "red")
35 lable.grid()
36 lablel1 = Label(root,text = "翻译后的内容为:",font = ("微软雅黑"),fg = "green")
37 lablel1.grid()
38  
39 res = StringVar()
40  
41 #输入控件
42 entry = Entry(root,font = ("微软雅黑",14))
43 entry.grid(row = 0,column = 1)
44 #翻译之后的结果
45 entry1 = Entry(root,font = ("微软雅黑",14),textvariable = res)
46 entry1.grid(row = 1,column = 1)
47  
48 #按钮控件   sticky对齐方式  N S E W - 上下左右
49 button = Button(root,text = "翻译",font = ("微软雅黑",13),command = translation)
50 button.grid(row = 2,column = 0,sticky = W)
51 button1 = Button(root,text = "退出",font = ("微软雅黑",13),command = root.quit)
52 button1.grid(row = 2,column = 1,sticky = E)
53  
54 #消息循环、显示窗口
55 root.mainloop()

原理非常简单,运用用户输入的关键字对搜狗在线翻译提交post请求然后返回数据显示在文本框内即可~

猜你喜欢

转载自www.cnblogs.com/diyi/p/9426682.html