使用python为下列代码加上一个GUI,类似聊天窗口,要求:ip地址和接口号在代码中确认,不能更改。代码:# 英文输入端 import socket import time import requests host = "192.168.185.60" # 服务器端可以写"localhost",可以为空字符串"",也为本机IP地址 port = 8888 # 端口号 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) conn, addr = s.accept() print('connected with', addr) while True: data = conn.recv(1024) data = data.decode() data1 = {'doctype': 'json', 'type': 'zh_TW', 'i': ''} data1['i'] = data r = requests.get("http://fanyi.youdao.com/translate", params=data1) # 访问翻译网站 result = r.json() # 获取翻译内容 t1 = result.setdefault('translateResult') t2 = t1[0] t3 = t2[0] # 解层翻译内容 if not data: break localTime = time.asctime(time.localtime(time.time())) print(localTime, 'receive:', t3.setdefault('tgt')) send = input('send:') conn.sendall(send.encode()) conn.close() s.close()
时间: 2024-03-08 10:45:11 浏览: 76
以下是一个使用Python Tkinter库实现的GUI版本的代码:
```python
import socket
import time
import requests
import tkinter as tk
HOST = "192.168.185.60" # 服务器端可以写"localhost",可以为空字符串"",也为本机IP地址
PORT = 8888 # 端口号
class ChatWindow:
def __init__(self, master):
self.master = master
self.master.geometry('500x500')
self.master.title('英文翻译聊天室')
self.master.protocol('WM_DELETE_WINDOW', self.close_window)
self.create_widgets()
self.connect_to_server()
def create_widgets(self):
self.chat_label = tk.Label(self.master, text='聊天记录')
self.chat_label.pack()
self.chat_text = tk.Text(self.master, height=20)
self.chat_text.pack()
self.input_label = tk.Label(self.master, text='输入框')
self.input_label.pack()
self.input_text = tk.Text(self.master, height=5)
self.input_text.pack()
self.send_button = tk.Button(self.master, text='发送', command=self.send_message)
self.send_button.pack()
def connect_to_server(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((HOST, PORT))
self.chat_text.insert(tk.END, '已连接到服务器\n')
def send_message(self):
message = self.input_text.get('1.0', tk.END).strip()
self.input_text.delete('1.0', tk.END)
if not message:
return
self.sock.sendall(message.encode())
self.chat_text.insert(tk.END, f'发送:{message}\n')
self.receive_message()
def receive_message(self):
data = self.sock.recv(1024)
data = data.decode()
if data:
self.chat_text.insert(tk.END, f'接收:{data}\n')
def close_window(self):
self.sock.close()
self.master.destroy()
def translate(text):
data1 = {'doctype': 'json', 'type': 'zh_TW', 'i': text}
r = requests.get("http://fanyi.youdao.com/translate", params=data1)
result = r.json()
t1 = result.setdefault('translateResult')
t2 = t1[0]
t3 = t2[0]
return t3.setdefault('tgt')
if __name__ == '__main__':
root = tk.Tk()
chat_window = ChatWindow(root)
while True:
root.update()
try:
chat_window.receive_message()
except socket.error:
break
time.sleep(0.05)
```
运行代码后,会弹出一个聊天窗口,可以在其中输入文字并发送,程序会通过网络连接发送给指定的服务器。服务器会将收到的文字翻译成中文并返回,程序会将翻译结果显示在聊天窗口中。在窗口关闭前,程序会一直循环接收和发送消息。
阅读全文