初级python代码编程学习----简单聊天机器人小程序 入门必看

聊天机器人程序

              今天来学习一个简单的聊天程序。使用下面的代码保存为.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) 。你可以输入命令,比如 hellobye,程序会相应地回应。这是一个非常基础的聊天程序,你可以根据需要添加更多的命令和功能。

如果你想要一个图形用户界面(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()

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值