python Tkinter + 百度翻译API 制作翻译脚本

import requests
import random
import json
import win32com.client
from hashlib import md5
import tkinter as tk

root = tk.Tk()
root.title("英语翻译")

root.geometry("600x300+630+80") # 乘号是小写字母x

btn1["text

添加 标签控件

label = tk.Label(root, text="")
label.grid()
text1 = tk.Text(root, width=35, height=10, state="normal")
text1.grid(row=1, column=1)

text2 = tk.Text(root, width=35, height=10, state="normal")
text2.grid(row=1, column=4)

def make_md5(s, encoding='utf-8'):
return md5(s.encode(encoding)).hexdigest()

def get():
inp = text1.get(1.0, 2.1)
print("你输入了:" + inp)
# appid = 'INPUT_YOUR_APPID'
appid = '10230128001541715'
appkey = 'IU0Ttt6lnOlNyKuoHH8y'
# appkey = 'INPUT_YOUR_APPKEY'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang = 'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path
query = inp

# Generate salt and sign
salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)

# Build request
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

# Send request
r = requests.post(url, params=payload, headers=headers)
result = r.json()
# print(result)
trans_result = result['trans_result'][0]['dst']
print('trans_result:', trans_result)

# Show response
# print(json.dumps(result, indent=4, ensure_ascii=False))
text2.delete(1.0, "end")
text2.insert(2.0, trans_result)
return 0

def get2():
inp = text1.get(1.0, 2.1)
# print("你输入了:" + inp)
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak(inp)

btn1 = tk.Button(root, text="翻译:", command=get)
btn1.grid(row=1, column=2)
btn2 = tk.Button(root, text="发音:", command=get2)
btn2.grid(row=1, column=3)

root.mainloop()

posted @ 2023-02-25 18:05  未来全栈攻城狮  阅读(74)  评论(0编辑  收藏  举报