import tkinter as tk
from tkinter import messagebox
import requests
from tkinter import ttk

chat_history = []

def send_message():
    global chat_history
    
    message_text = message_entry.get()
    if not message_text:
        return
    
    chat_history.append(f'你: {message_text}
')
    
    chat_box.config(state=tk.NORMAL)
    chat_box.insert(tk.END, chat_history[-1], 'right_align')
    chat_box.see(tk.END)
    chat_box.config(state=tk.DISABLED)
    message_entry.delete(0, tk.END)

    # 显示动态等待效果
    wait_label.config(text='等待响应中...', fg='gray')
    root.update()

    # 获取前10次的对话记录
    chat_history_to_send = ''.join(chat_history[-20:-1])
    chat_history_to_send += chat_history[-1]

    # 发送网络请求
    response = requests.get('https://chatgpt-chatpt-zggoappkts.cn-beijing.fcapp.run', params={'content': message_text, 'chat_history': chat_history_to_send})

    if response.status_code == 200:
        response_text = response.text
        chat_history.append(f'chatgpt: {response_text}

')
        chat_box.config(state=tk.NORMAL)
        chat_box.insert(tk.END, chat_history[-1], 'left_align')
        chat_box.see(tk.END)
        chat_box.config(state=tk.DISABLED)
        wait_label.config(text='')
        
        # 保存消息到本地
        with open('chat_history.txt', 'a') as f:
            f.write(chat_history[-2])
            f.write(chat_history[-1])
    else:
        messagebox.showerror('错误', f'服务器状态码 {response.status_code}')
        wait_label.config(text='')
        
def load_chat_history():
    try:
        with open('chat_history.txt', 'r') as f:
            chat_history.extend(f.readlines())
            chat_box.config(state=tk.NORMAL)
            for message in chat_history:
                if message.startswith('你:'):
                    chat_box.insert(tk.END, message, 'right_align')
                elif message.startswith('chatgpt:'):
                    chat_box.insert(tk.END, message, 'left_align')
            chat_box.see(tk.END)
            chat_box.config(state=tk.DISABLED)
    except FileNotFoundError:
        pass
    
root = tk.Tk()
root.title('Chatgpt by 果然多cc果卷')

# 添加样式
style = ttk.Style()
style.configure('right_align.TLabel', anchor='e')
style.configure('left_align.TLabel', anchor='w')
style.configure('center_align.TLabel', justify='center')

# Material Design 颜色定义(蓝色)
primary_color = '#2196f3'
light_primary_color = '#6ec6ff'
dark_primary_color = '#0069c0'
text_primary_color = '#ffffff'
accent_color = '#4caf50'

# 创建聊天界面
chat_frame = tk.Frame(root, bg=primary_color)
chat_frame.pack(pady=(15, 0), fill='both', expand=True)

chat_box = tk.Text(chat_frame, height=20, width=50, state=tk.DISABLED, font=('Arial', 12), bg='white', fg='black', highlightbackground='#c5c5c5', highlightthickness=1)
chat_box.pack(side=tk.LEFT, padx=(0, 10), pady=(0, 5), fill='both', expand=True)

scrollbar = tk.Scrollbar(chat_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

message_entry = tk.Entry(root, width=50, font=('Arial', 12), relief='flat')
message_entry.pack(padx=10, pady=10, ipady=8, fill='x')

send_button = tk.Button(root, text='发送', command=send_message, font=('Arial', 12), bg=accent_color, fg=text_primary_color, bd=0, padx=20, pady=10)
send_button.pack(side=tk.BOTTOM, padx=10, pady=(0, 10))

wait_label = tk.Label(root, text='', font=('Arial', 12), fg=primary_color)
wait_label.pack(pady=(0, 10))

chat_box.tag_configure('right_align', foreground=light_primary_color, font=('Arial', 12, 'bold'))
chat_box.tag_configure('left_align', foreground=dark_primary_color, font=('Arial', 12, 'bold'))
chat_box.tag_configure('center_align', font=('Arial', 12))

chat_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=chat_box.yview)

load_chat_history()  # 加载聊天历史记录

# 设置窗口背景颜色和大小
root.configure(bg=primary_color)
root.geometry('400x550')
root.resizable(False, False)
root.bind('<Return>', lambda event: send_button.invoke())

root.mainloop()

代码解析:

  1. 发送消息函数 send_message()

    • 获取输入框 message_entry 的文本内容。
    • 将文本内容添加到聊天历史列表 chat_history 中,并显示在聊天框 chat_box 中。
    • chat_history 中获取前 10 次的对话记录,并将其拼接成一个字符串 chat_history_to_send
    • 发送网络请求,将输入文本和聊天历史记录作为参数传递给服务器。
    • 接收服务器返回的响应,并将其显示在聊天框中。
    • 保存聊天记录到本地文件 chat_history.txt
  2. 加载聊天历史记录函数 load_chat_history()

    • 从本地文件 chat_history.txt 加载聊天记录,并显示在聊天框中。
    • 如果文件不存在,则不进行任何操作。
  3. 主程序

    • 创建 Tkinter 窗口 root
    • 创建聊天界面 chat_frame
    • 创建聊天框 chat_box 、输入框 message_entry 、发送按钮 send_button 、等待标签 wait_label
    • 添加聊天框的样式和颜色。
    • 绑定回车键,实现按下回车键发送消息的功能。
    • 加载聊天历史记录。
    • 启动主循环 root.mainloop()

注意:

  • 服务器地址 https://chatgpt-chatpt-zggoappkts.cn-beijing.fcapp.run 需要替换成实际的 ChatGPT API 服务器地址。
  • 可以根据需要修改聊天记录保存的路径和文件名。
  • 可以根据自己的需求调整界面样式和颜色。
  • 可以添加其他功能,例如语音输入、表情符号、自动换行等。
基于Tkinter的ChatGPT聊天机器人界面(支持聊天历史记录)

原文地址: https://www.cveoy.top/t/topic/lIJP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录