聊天机器人程序
今天来学习一个简单的聊天程序。使用下面的代码保存为.py。方法可以查看第一篇博文。例如保存为123.py。
import cmd
class ChatBot(cmd.Cmd):
prompt = '(chat) '
def do_hello(self, arg):
"""Responds to a greeting."""
print("你好!我是人工智能助手。有什么可以帮助你的吗?")
def do_bye(self, arg):
"""Exits the chat."""
print("再见!很高兴和你聊天。")
return True # 返回 True 表示退出程序
def default(self, line):
"""Handles any input that doesn't match a command."""
print("不好意思,我不明白你的意思。")
def emptyline(self):
"""Does nothing when the user just hits enter."""
pass
if __name__ == '__main__':
ChatBot().cmdloop()
电脑安装python环境后在cmd指令中中运行这个py
python 123.py
程序启动后,你会在命令行看到一个提示 (chat)
。你可以输入命令,比如 hello
或 bye
,程序会相应地回应。这是一个非常基础的聊天程序,你可以根据需要添加更多的命令和功能。
如果你想要一个图形用户界面(GUI)聊天程序,可以使用 tkinter
库来创建。以下是一个简单的 tkinter
聊天程序示例:
import tkinter as tk
from tkinter import scrolledtext
class ChatApp:
def __init__(self, root):
self.root = root
self.root.title("简单聊天程序")
self.text = scrolledtext.ScrolledText(root, state='disabled', wrap=tk.WORD)
self.text.pack(fill=tk.BOTH, expand=True)
self.entry = tk.Entry(root)
self.entry.pack(fill=tk.X, expand=True)
self.send_button = tk.Button(root, text="发送", command=self.send)
self.send_button.pack(side=tk.BOTTOM, fill=tk.X)
self.bind("<Return>", self.send)
def send(self):
"""发送消息到聊天窗口,并清除输入框。"""
user_input = self.entry.get()
if user_input:
self.text.configure(state='normal')
self.text.insert(tk.END, "你: " + user_input + "\n")
self.text.configure(state='disabled')
self.entry.delete(0, tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = ChatApp(root)
root.mainloop()
同样,将这段代码保存到一个 .py
文件中,并运行它。这将启动一个简单的 GUI 聊天程序。
那么如何使用tkinter来创建
tkinter
是 Python 的标准 GUI 库,用于创建图形用户界面(GUI)。以下是如何使用 tkinter
库创建一个简单窗口的基本步骤:
安装 tkinter
Python 的标准库中包含了 tkinter
,因此通常不需要额外安装。如果你的 Python 环境中没有 tkinter
,你需要安装它,但通常不需要,因为它是 Python 的一部分。
创建一个简单的窗口
以下是一个创建基本窗口的简单示例:
import tkinter as tk
# 创建主窗口
root = tk.Tk()
# 设置窗口标题
root.title("简单窗口")
# 设置窗口大小
root.geometry("300x200")
# 创建一个标签
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
# 运行主循环
root.mainloop()