|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 lixiangyv 于 2020-3-27 07:36 编辑
第 1 版的聊天室只能在服务器上查看的发送消息,这次这个问题解决了^_^
而且还做了 GUI 的界面。
最终的效果图:
附件:
聊天助手.rar
(2.18 KB, 下载次数: 6)
源代码:
客户端:
import socket
import time
from threading import *
from tkinter import *
from random import choice
from tkinter.messagebox import showwarning
class ChatHelper():
chat = None
nick_list = ['黑猫警长', '小脚鱼', '喜洋洋', '冰冰羊']
def __init__(self, chat):
"""
初始化
:param chat:
"""
self.chat = chat
self.init_ui()
def init_ui(self):
"""
初始化图形界面
:return:
"""
window = Tk()
window.title('聊天助手')
# 是窗口不可变
window.resizable(False, False)
# 聊天显示
self.area = Text(window, borderwidth=2, relief="groove", width=53, height=16, bg="seashell", font=("微软雅黑", 16))
self.area.grid(row=0, column=0, columnspan=3)
# 聊天文字样式
self.area.tag_config('me', background="#34ACFF", foreground="white")
self.area.tag_config('others', background="#ABB8C0", foreground="white")
self.area.tag_config('warn', background="orange", foreground="white")
self.area.tag_config('success', background="#34D361", foreground="white")
# 文字输入框
self.input = Entry(window, width=44, font=("微软雅黑", 16))
self.input.grid(row=1, column=0, columnspan=2, pady=10)
# 发送按钮
btn = Button(window, text=" 发送 ", command=self.send_message)
btn.grid(row=1, column=2)
label = Label(window, text='你的昵称:')
label.grid(row=2, column=0, sticky=W, padx=5, pady=10)
# 昵称输入框
self.nick = Entry(window, width=38, font=("微软雅黑", 16))
self.nick.grid(row=2, column=1, pady=10)
self.nick.insert(0, self.next_nick())
# 昵称刷新按钮
ref = Button(window, text='换一个', command=self.ref_nick)
ref.grid(row=2, column=2)
def send_message(self):
# 获取文本框的内容
sendMsg = self.input.get()
nick = self.nick.get()
if (not sendMsg) or (not nick):
showwarning(title='警告', message="你发送的消息或者昵称为空!")
self.chat.sendData(nick, sendMsg)
def next_nick(self):
return choice(self.nick_list)
def ref_nick(self):
self.nick.delete(0, END)
self.nick.insert(0, self.next_nick())
# 创建多线程
class MessageHelper(Thread):
chatHelper = None
client = None
SERVERHOST = ('127.0.0.1', 8888)
def run(self):
# 等待一秒,便于计算机连接
time.sleep(1)
self.connect()
def connect(self):
# 创建套接字
self.client = socket.socket()
self.client.connect(self.SERVERHOST)
# 接受服务器的消息
while True:
msg = self.client.recv(1024).decode()
nick, text = msg.split(":")
if nick == self.chatHelper.nick.get():
self.chatHelper.area.insert(END, f"我:{text}", "me")
elif nick == '系统消息':
self.chatHelper.area.insert(END, f"{text}", "success")
else:
self.chatHelper.area.insert(END, f"{nick}:{text}", "others")
self.chatHelper.area.see(END)
def sendData(self, nick, message):
self.client.send(bytes(nick + ":" + message, "utf-8"))
def set_chathelper(self, ch):
self.chatHelper = ch
mh = MessageHelper()
mh.start()
ch = ChatHelper(mh)
mh.set_chathelper(ch)
mainloop()
服务端:import socket
import time
from threading import *
from tkinter import *
from random import choice
from tkinter.messagebox import showwarning
class ChatHelper():
chat = None
nick_list = ['黑猫警长', '小脚鱼', '喜洋洋', '冰冰羊']
def __init__(self, chat):
"""
初始化
:param chat:
"""
self.chat = chat
self.init_ui()
def init_ui(self):
"""
初始化图形界面
:return:
"""
window = Tk()
window.title('聊天助手')
# 是窗口不可变
window.resizable(False, False)
# 聊天显示
self.area = Text(window, borderwidth=2, relief="groove", width=53, height=16, bg="seashell", font=("微软雅黑", 16))
self.area.grid(row=0, column=0, columnspan=3)
# 聊天文字样式
self.area.tag_config('me', background="#34ACFF", foreground="white")
self.area.tag_config('others', background="#ABB8C0", foreground="white")
self.area.tag_config('warn', background="orange", foreground="white")
self.area.tag_config('success', background="#34D361", foreground="white")
# 文字输入框
self.input = Entry(window, width=44, font=("微软雅黑", 16))
self.input.grid(row=1, column=0, columnspan=2, pady=10)
# 发送按钮
btn = Button(window, text=" 发送 ", command=self.send_message)
btn.grid(row=1, column=2)
label = Label(window, text='你的昵称:')
label.grid(row=2, column=0, sticky=W, padx=5, pady=10)
# 昵称输入框
self.nick = Entry(window, width=38, font=("微软雅黑", 16))
self.nick.grid(row=2, column=1, pady=10)
self.nick.insert(0, self.next_nick())
# 昵称刷新按钮
ref = Button(window, text='换一个', command=self.ref_nick)
ref.grid(row=2, column=2)
def send_message(self):
# 获取文本框的内容
sendMsg = self.input.get()
nick = self.nick.get()
if (not sendMsg) or (not nick):
showwarning(title='警告', message="你发送的消息或者昵称为空!")
self.chat.sendData(nick, sendMsg)
def next_nick(self):
return choice(self.nick_list)
def ref_nick(self):
self.nick.delete(0, END)
self.nick.insert(0, self.next_nick())
# 创建多线程
class MessageHelper(Thread):
chatHelper = None
client = None
SERVERHOST = ('127.0.0.1', 8888)
def run(self):
# 等待一秒,便于计算机连接
time.sleep(1)
self.connect()
def connect(self):
# 创建套接字
self.client = socket.socket()
self.client.connect(self.SERVERHOST)
# 接受服务器的消息
while True:
msg = self.client.recv(1024).decode()
nick, text = msg.split(":")
if nick == self.chatHelper.nick.get():
self.chatHelper.area.insert(END, f"我:{text}", "me")
elif nick == '系统消息':
self.chatHelper.area.insert(END, f"{text}", "success")
else:
self.chatHelper.area.insert(END, f"{nick}:{text}", "others")
self.chatHelper.area.see(END)
def sendData(self, nick, message):
self.client.send(bytes(nick + ":" + message, "utf-8"))
def set_chathelper(self, ch):
self.chatHelper = ch
mh = MessageHelper()
mh.start()
ch = ChatHelper(mh)
mh.set_chathelper(ch)
mainloop()
|
评分
-
查看全部评分
|