帮我用python写一个gui聊天室,完整源码
时间: 2024-03-25 20:38:20 浏览: 142
好的,以下是一个简单的Python GUI聊天室的完整源码,基于Tkinter库实现:
```python
import tkinter as tk
from tkinter import scrolledtext, messagebox
import socket
import threading
class ChatRoomGUI:
def __init__(self, master):
self.master = master
self.master.title("Chat Room")
self.master.resizable(0, 0)
self.create_widgets()
def create_widgets(self):
self.label_ip = tk.Label(self.master, text="Server IP:")
self.label_ip.grid(row=0, column=0, padx=(10, 0), pady=(10, 5))
self.entry_ip = tk.Entry(self.master)
self.entry_ip.insert(tk.END, "127.0.0.1")
self.entry_ip.grid(row=0, column=1, padx=(0, 10), pady=(10, 5))
self.label_port = tk.Label(self.master, text="Port:")
self.label_port.grid(row=1, column=0, padx=(10, 0), pady=5)
self.entry_port = tk.Entry(self.master)
self.entry_port.insert(tk.END, "55555")
self.entry_port.grid(row=1, column=1, padx=(0, 10), pady=5)
self.button_connect = tk.Button(self.master, text="Connect", command=self.connect)
self.button_connect.grid(row=0, column=2, rowspan=2, padx=10, pady=5)
self.label_username = tk.Label(self.master, text="Username:")
self.label_username.grid(row=2, column=0, padx=(10, 0), pady=(10, 5))
self.entry_username = tk.Entry(self.master)
self.entry_username.grid(row=2, column=1, columnspan=2, padx=(0, 10), pady=(10, 5))
self.text_chat = scrolledtext.ScrolledText(self.master, state=tk.DISABLED)
self.text_chat.grid(row=3, column=0, columnspan=3, padx=10, pady=5)
self.entry_message = tk.Entry(self.master)
self.entry_message.bind("<Return>", self.send)
self.entry_message.grid(row=4, column=0, columnspan=2, padx=(10, 0), pady=(5, 10))
self.button_send = tk.Button(self.master, text="Send", command=self.send)
self.button_send.grid(row=4, column=2, padx=(0, 10), pady=(5, 10))
def connect(self):
try:
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.connect((self.entry_ip.get(), int(self.entry_port.get())))
self.client_socket.send(self.entry_username.get().encode())
self.master.title("Chat Room - " + self.entry_username.get())
self.text_chat.config(state=tk.NORMAL)
self.text_chat.insert(tk.END, "Connected to server.\n")
self.text_chat.config(state=tk.DISABLED)
self.thread_receive = threading.Thread(target=self.receive)
self.thread_receive.start()
except ConnectionRefusedError:
messagebox.showerror("Error", "Connection refused. Server is not running.")
except OSError:
messagebox.showerror("Error", "Invalid IP or port.")
def send(self, event=None):
message = self.entry_message.get()
if message:
self.client_socket.send(message.encode())
self.entry_message.delete(0, tk.END)
def receive(self):
while True:
try:
message = self.client_socket.recv(1024).decode()
if message == "USERNAME":
self.client_socket.send(self.entry_username.get().encode())
else:
self.text_chat.config(state=tk.NORMAL)
self.text_chat.insert(tk.END, message + "\n")
self.text_chat.config(state=tk.DISABLED)
self.text_chat.yview(tk.END)
except OSError:
break
self.client_socket.close()
self.master.title("Chat Room - Disconnected")
if __name__ == "__main__":
root = tk.Tk()
app = ChatRoomGUI(root)
root.mainloop()
```
这个聊天室使用了Python的socket和threading模块,以及Tkinter库来创建GUI界面。用户需要输入服务器的IP地址和端口号,以及自己的用户名,然后点击“Connect”按钮连接到服务器。连接成功后,用户可以在文本框中输入消息并按回车或点击“Send”按钮发送消息。接收到消息后,程序会将其显示在聊天室的文本框中。如果服务器未启动或IP地址或端口号无效,程序会显示错误消息框。
阅读全文