python实现简易聊天对话框
程序员文章站
2022-03-02 18:30:55
本文实例为大家分享了python实现简易聊天对话框的具体代码,供大家参考,具体内容如下效果图:客户端代码:import tkinter as tkfrom tkinter import scrolle...
本文实例为大家分享了python实现简易聊天对话框的具体代码,供大家参考,具体内容如下
效果图:
客户端代码:
import tkinter as tk from tkinter import scrolledtext import socket import threading from datetime import datetime def tcp_recv(sock): while true: str = sock.recv(1024).decode("utf-8") show_info(str) def send_func(sock): str = send_msg.get("0.0", "end") sock.send(str.encode("utf-8")) show_info(str) def show_info(str): now = datetime.now() s_time = now.strftime("%y-%m-%d %h:%m:%s") str = str.rstrip() if len(str) == 0: return -1 send_msg.delete("0.0", "end") temp = s_time + "\n " + str + "\n" show_msg.insert(tk.insert, "%s" % temp) msfont = '微软雅黑' #字体 fontsize = 18 #字体大小 sock = socket.socket(socket.af_inet,socket.sock_stream) sock.connect(("127.0.0.1",8888)) mainwindow = tk.tk() mainwindow.title("客户端") mainwindow.minsize(400,400) show_msg = scrolledtext.scrolledtext(mainwindow,font=(msfont,fontsize)) show_msg.place(width=400,height=250,x=0,y=0) #show_msg.insert(tk.insert,"%s 已连接\n"%addr[0]) send_msg = scrolledtext.scrolledtext(mainwindow,font=(msfont,fontsize)) send_msg.place(width=400,height=140,x=0,y=260) button_send = tk.button( mainwindow, font=(msfont,fontsize),text = "发 送",bg="orange",fg="white", command=lambda:send_func(sock)) button_send.place(width=100,height=40,x=300,y=360) t = threading.thread(target=tcp_recv,args=(sock,)) t.start() tk.mainloop()
服务器代码:
import tkinter as tk from tkinter import scrolledtext import socket import threading from datetime import datetime def tcp_recv(sock): while true: str = sock.recv(1024).decode("utf-8") show_info(str) def send_func(sock): str = send_msg.get("0.0", "end") sock.send(str.encode("utf-8")) show_info(str) def show_info(str): now = datetime.now() s_time = now.strftime("%y-%m-%d %h:%m:%s") str = str.rstrip() if len(str) == 0: return -1 send_msg.delete("0.0", "end") temp = s_time + "\n " + str + "\n" show_msg.insert(tk.insert, "%s" % temp) msfont = '微软雅黑' #字体 fontsize = 18 #字体大小 sock = socket.socket(socket.af_inet,socket.sock_stream) sock.bind(("127.0.0.1",8888)) sock.listen(5) mainwindow = tk.tk() mainwindow.title("服务器") mainwindow.minsize(400,400) show_msg = scrolledtext.scrolledtext(mainwindow,font=(msfont,fontsize)) show_msg.place(width=400,height=250,x=0,y=0) send_msg = scrolledtext.scrolledtext(mainwindow,font=(msfont,fontsize)) send_msg.place(width=400,height=140,x=0,y=260) button_send = tk.button( mainwindow, font=(msfont,fontsize),text = "发 送",bg="orange",fg="white", command=lambda:send_func(s)) button_send.place(width=100,height=40,x=300,y=360) s,addr = sock.accept() t = threading.thread(target=tcp_recv,args=(s,)) t.start() tk.mainloop()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 详细全面解析Java泛型