Python 聊天室窗口能夠讓我們實時地與朋友、同事和團隊成員交流,提高溝通效率和工作效率。我們可以通過 Python 編程語言構(gòu)建自己的聊天室程序,接下來讓我們來看一下相應(yīng)的代碼。
import tkinter as tk from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import time def receive(): while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") msg_list.insert(tk.END, msg) except OSError: break def send(event=None): msg = my_msg.get() my_msg.set("") client_socket.send(bytes(msg, "utf8")) if msg == "{quit}": client_socket.close() top.quit() def on_closing(event=None): my_msg.set("{quit}") send() top = tk.Tk() top.title("Python 聊天室") messages_frame = tk.Frame(top) my_msg = tk.StringVar() my_msg.set("在這里輸入消息") scrollbar = tk.Scrollbar(messages_frame) msg_list = tk.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) msg_list.pack(side=tk.LEFT, fill=tk.BOTH) msg_list.pack() messages_frame.pack() entry_field = tk.Entry(top, textvariable=my_msg) entry_field.bind("", send) entry_field.pack() send_button = tk.Button(top, text="發(fā)送", command=send) send_button.pack() top.protocol("WM_DELETE_WINDOW", on_closing) HOST = "localhost" PORT = 33000 BUFSIZ = 1024 ADDR = (HOST, PORT) client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(ADDR) receive_thread = Thread(target=receive) receive_thread.start() tk.mainloop()
在這段 Python 代碼中,我們利用 tkinter 模塊來構(gòu)建用戶界面,使用 socket 模塊進行網(wǎng)絡(luò)通信,并且通過 threading 模塊實現(xiàn)多線程處理來接收服務(wù)器的消息。使用此聊天室窗口時,只需要輸入消息并點擊發(fā)送按鈕即可。
上一篇vue原因怎么去掉