您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用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()
“怎么用python實現簡易聊天對話框”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。