1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| import tkinter from tkinter import font import tkinter.messagebox import socket import threading import time
string = ''
def Send(sock):
if string != '': message = name + ' : ' + string sock.send(message.encode('utf-8'))
if 'exit' in string.lower(): exit(0)
def recv(sock): sock.send(name.encode('utf-8')) while True: data = sock.recv(1024) time_tuple = time.localtime(time.time()) str = ("{}-{}-{} {}:{}:{}".format(time_tuple[0],time_tuple[1],time_tuple[2],time_tuple[3], time_tuple[4],time_tuple[5])) time_recv = tkinter.Label(t,text=str,width=40,anchor='w') time_recv.pack() if "enter the room" in data.decode('utf-8'): rrecv = tkinter.Label(t, text=data.decode('utf-8'), width=40, anchor='w',bg='powderblue') elif "left the room" in data.decode('utf-8'): rrecv = tkinter.Label(t, text=data.decode('utf-8'), width=40, anchor='w', bg='pink') else: rrecv = tkinter.Label(t, text=data.decode('utf-8'), width=40, anchor='w') rrecv.pack()
def left(): global string string = rv1.get() Send(s) if string != '': time_tuple = time.localtime(time.time()) str = ("{}-{}-{} {}:{}:{}".format(time_tuple[0],time_tuple[1],time_tuple[2],time_tuple[3], time_tuple[4],time_tuple[5])) time_send = tkinter.Label(t,text=str,width=40,anchor='e') time_send.pack() rleft = tkinter.Label(t, text=string, width=40, anchor='e') rleft.pack() rv1.set('')
def Creat(): global name name = n.get() tr = threading.Thread(target=recv, args=(s,), daemon=True) tr.start() l.destroy() e.destroy() b.destroy() t.title("chatroom") t.geometry("400x500") rL0 = tkinter.Label(t, text='%s' % name, width=40) rL0.pack() rE1 = tkinter.Entry(t, textvariable=rv1,width=40) rE1.place(x=1, y=450) rB1 = tkinter.Button(t, text="send", width=7, height=1, command=left) rB1.place(x=320, y=450)
def close_chat(): tkinter.messagebox.showwarning(title='exit', message='exit?') s.send("break the link".encode('utf-8')) exit(0)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server = ('127.0.0.1', 12000) s.connect(server)
t = tkinter.Tk() t.title("chat") t.geometry("300x270+500+200")
l = tkinter.Label(t, text='please input your nickname', width=40, height=10,font=('黑体',15,'')) l.pack() n = tkinter.StringVar() e = tkinter.Entry(t, width=20, textvariable=n,font=('黑体',15,'')) e.pack() rv1 = tkinter.StringVar()
name = n.get() b = tkinter.Button(t, text="login", width=30, height=40, command=Creat) b.pack()
t.protocol("WM_DELETE_WINDOW", close_chat)
t.mainloop()
s.close()
|