用pycharm且不使用flask设计一款聊天机器人app
时间: 2024-01-24 14:17:15 浏览: 84
设计一个聊天机器人app可以使用Python中的Tkinter模块来创建GUI界面,使用Python内置的socket模块来实现网络通信,使用Python中的多线程模块来实现同时处理多个客户端请求的功能。
以下是一个简单的聊天机器人app的代码示例:
```python
import tkinter as tk
import socket
import threading
class ChatClient:
def __init__(self, host, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.buffer_size = 1024
def send_msg(self, msg):
self.sock.send(msg.encode('utf-8'))
def recv_msg(self):
data = self.sock.recv(self.buffer_size)
return data.decode('utf-8')
class ChatApp:
def __init__(self, master):
self.master = master
master.title('ChatBot')
self.chat_client = None
self.msg_listbox = tk.Listbox(master)
self.msg_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.msg_entry = tk.Entry(master)
self.msg_entry.bind('<Return>', self.send_msg)
self.msg_entry.pack(side=tk.BOTTOM, fill=tk.X, expand=True)
self.connect_button = tk.Button(master, text='Connect', command=self.connect)
self.connect_button.pack(side=tk.TOP)
self.disconnect_button = tk.Button(master, text='Disconnect', command=self.disconnect, state=tk.DISABLED)
self.disconnect_button.pack(side=tk.TOP)
self.quit_button = tk.Button(master, text='Quit', command=self.quit)
self.quit_button.pack(side=tk.TOP)
def connect(self):
self.chat_client = ChatClient('localhost', 5000)
self.connect_button.config(state=tk.DISABLED)
self.disconnect_button.config(state=tk.NORMAL)
threading.Thread(target=self.recv_msg).start()
def disconnect(self):
self.chat_client.sock.close()
self.connect_button.config(state=tk.NORMAL)
self.disconnect_button.config(state=tk.DISABLED)
def send_msg(self, event):
msg = self.msg_entry.get()
self.msg_entry.delete(0, 'end')
self.msg_listbox.insert(tk.END, 'You: {}'.format(msg))
self.chat_client.send_msg(msg)
def recv_msg(self):
while True:
data = self.chat_client.recv_msg()
if not data:
break
self.msg_listbox.insert(tk.END, 'Bot: {}'.format(data))
def quit(self):
if self.chat_client:
self.chat_client.sock.close()
self.master.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = ChatApp(root)
root.mainloop()
```
这个程序使用了Tkinter模块创建了一个GUI界面,包括一个消息列表框和一个消息输入框。程序还创建了一个ChatClient类来处理与服务器的网络通信,并使用多线程来同时处理客户端接收和发送消息的功能。程序的主要逻辑在ChatApp类中实现,包括连接、断开连接、发送消息和接收消息等功能。
阅读全文