客户端窗口显示
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import socket
import datetime
import threading
from tkinter import *
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 8888))
sock.send(b'1')
#nickName = input('请输入自己的昵称:')
#s = Listbox(root)
def receivemsg():
while True:
otherword = sock.recv(1024)
if otherword:
text_msglist.config(state = NORMAL)
text_msglist.insert(END ,otherword.decode())
text_msglist.config(state = DISABLED)
#text_msglist = Text(frame_left_top,state=DISABLED)
root = Tk()
root.title(('聊天室聊天中(首先请输入昵称)'))
# 创建几个frame作为容器
# frame_left_top = Label(width=50, height=20, bg='white')
# frame_left_center = Label(width=50, height=10, bg='white')
# frame_left_bottom = Label(width=5, height=3)
frame_left_top = Frame(width=380, height=270, bg='white')
frame_left_center = Frame(width=380, height=150, bg='white')
frame_left_bottom = Frame(width=380, height=30)
scrollbar = Scrollbar(frame_left_top,orient=VERTICAL)
scrollbar.pack(fill=Y,side=RIGHT)
# 创建几个元素
def sendmessage(event=1):
msgcontent = ('我:') + \
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n'
text_msglist.config(state=NORMAL)
text_msglist.insert(END, msgcontent, 'greeen')
text_msglist.insert(END, text_msg.get('0.0', END))
text_msglist.config(state=DISABLED)
if text_msg.get('0.0', END).strip() != '' :
print(text_msg.get('0.0', END).encode())
sock.send(text_msg.get('0.0', END).encode())
text_msg.delete('0.0', END)
text_msglist = Text(frame_left_top,state=DISABLED,yscrollcommand=scrollbar.set)
text_msg = Text(frame_left_center)
button_sendmsg= Button(frame_left_bottom, text='发送', command=sendmessage)
root.bind("<Return>",sendmessage)
button_sendmsg.pack()
scrollbar.config(command=text_msglist.yview)
# 创建一个绿色的tag
text_msglist.tag_config('green', foreground='#008B00')
#text_msglist.config(frame_left_top,command=DISABLED)
# 使用grid设置几个容器得位置
frame_left_top.pack(fill =X)
frame_left_center.pack(fill = X)
frame_left_bottom.pack(anchor='e')
frame_left_top.propagate(False)
frame_left_center.propagate(False)
frame_left_bottom.propagate(False)
text_msglist.pack()
text_msg.pack()
th2 = threading.Thread(target=receivemsg)
th2.setDaemon(True)
th2.start()
# 主事件循环
root.mainloop()