使用python构建可以发送信息,文件,图片,并且附带GUI界面的聊天系统
时间: 2024-02-23 17:00:12 浏览: 142
基于python实现聊天室程序
好的,实现这个聊天系统需要用到以下 Python 库:
1. tkinter:Python 标准 GUI 库,可以创建和管理 GUI 应用程序的各种组件,包括窗口、按钮、文本框、标签等等。
2. socket:Python 标准库之一,可以用于创建网络套接字,实现网络通信。
3. pickle:Python 标准库之一,可以实现对象的序列化和反序列化,用于在网络传输中发送复杂数据类型。
4. Pillow:Python 图像处理库,可以操作图像文件,包括打开、保存、缩放、裁剪、旋转等等。
5. threading:Python 标准库之一,可以创建多线程程序,实现并发执行。
下面是一个简单的可以发送文字、文件和图片,带有 GUI 界面的聊天系统的示例代码:
```python
import tkinter as tk
import socket
import threading
import pickle
from PIL import Image, ImageTk
import os
class ChatClient:
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
self.receive_thread = threading.Thread(target=self.receive)
self.receive_thread.start()
def receive(self):
while True:
try:
data = self.socket.recv(1024)
if data:
message = pickle.loads(data)
if isinstance(message, str):
self.receive_message(message)
elif isinstance(message, bytes):
self.receive_file(message)
elif isinstance(message, dict):
self.receive_image(message)
except Exception as e:
print(e)
break
def send(self, message):
try:
self.socket.send(pickle.dumps(message))
except Exception as e:
print(e)
def receive_message(self, message):
self.message_box.config(state=tk.NORMAL)
self.message_box.insert(tk.END, message + '\n')
self.message_box.config(state=tk.DISABLED)
def receive_file(self, data):
filename, filedata = data.decode('utf-8').split('|')
with open(filename, 'wb') as f:
f.write(filedata.encode('utf-8'))
self.receive_message('Received file: ' + filename)
def receive_image(self, data):
filename, imagedata = data['filename'], data['imagedata']
with open(filename, 'wb') as f:
f.write(imagedata)
image = Image.open(filename).resize((200, 200))
photo = ImageTk.PhotoImage(image)
self.image_box.image = photo
self.image_box.config(image=photo)
def send_message(self, event=None):
message = self.message_input.get()
self.message_input.delete(0, tk.END)
if message:
self.send(message)
def send_file(self):
file_path = tk.filedialog.askopenfilename()
if file_path:
with open(file_path, 'rb') as f:
filedata = f.read().decode('utf-8')
filename = os.path.basename(file_path)
self.send(filename + '|' + filedata)
self.receive_message('Sent file: ' + filename)
def send_image(self):
file_path = tk.filedialog.askopenfilename()
if file_path:
with open(file_path, 'rb') as f:
imagedata = f.read()
filename = os.path.basename(file_path)
self.send({'filename': filename, 'imagedata': imagedata})
self.receive_message('Sent image: ' + filename)
def run(self):
self.window = tk.Tk()
self.window.title('Chat Client')
self.message_box = tk.Text(self.window, state=tk.DISABLED)
self.message_box.pack(side=tk.TOP, padx=10, pady=10)
self.scrollbar = tk.Scrollbar(self.window)
self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.message_box.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.message_box.yview)
self.message_input = tk.Entry(self.window)
self.message_input.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.X, expand=True)
self.message_input.bind("<Return>", self.send_message)
self.send_button = tk.Button(self.window, text='Send', command=self.send_message)
self.send_button.pack(side=tk.RIGHT, padx=10, pady=10)
self.file_button = tk.Button(self.window, text='Send File', command=self.send_file)
self.file_button.pack(side=tk.LEFT, padx=10, pady=10)
self.image_button = tk.Button(self.window, text='Send Image', command=self.send_image)
self.image_button.pack(side=tk.LEFT, padx=10, pady=10)
self.image_box = tk.Label(self.window)
self.image_box.pack(side=tk.BOTTOM, padx=10, pady=10)
self.window.mainloop()
if __name__ == '__main__':
client = ChatClient('localhost', 9999)
client.run()
```
注意:这是一个简单的示例代码,仅适用于学习和演示用途,实际使用中可能需要更严密的错误处理和安全性措施。
阅读全文