请使用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-04-26 08:24:39 浏览: 101
python简易聊天室代码
以下是使用Python tkinter库编写的GUI代码,实现了一个简单的聊天窗口,可以与上述代码进行通信。注意,IP地址和端口号在代码中已确认,不能更改。
```
import tkinter as tk
import socket
import time
import requests
# 创建窗口
window = tk.Tk()
window.title("Chat Window")
window.geometry("400x400")
# 创建文本框
text_box = tk.Text(window, height=20, width=50)
text_box.pack()
# 创建输入框
input_box = tk.Entry(window, width=50)
input_box.pack()
# 创建发送按钮
def send_message():
# 连接服务器
host = "192.168.185.60"
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# 发送消息
send = input_box.get()
s.sendall(send.encode())
# 接收消息
data = s.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]
localTime = time.asctime(time.localtime(time.time()))
text_box.insert(tk.END, localTime + " receive: " + t3.setdefault('tgt') + "\n")
# 关闭连接
s.close()
send_button = tk.Button(window, text="Send", command=send_message)
send_button.pack()
# 运行窗口
window.mainloop()
```
阅读全文