To create a Python chatbot GUI using OpenAI's API, we'll use Tkinter (for the GUI) and OpenAI's Python library (for the chat functionality). Below is a complete, working script:
Step 1: Install Dependencies
First, install the required packages:
pip install openai tkinter
Step 2: The Chatbot Script
import tkinter as tk
from tkinter import scrolledtext, messagebox
import openai
# Initialize global chat history (to maintain context)
chat_history = [{"role": "system", "content": "You are a helpful assistant."}]
def send_message():
"""Handle sending user messages and getting AI responses."""
user_input = entry_user.get().strip()
if not user_input:
return # Skip empty messages
# Display user message in chat area
chat_area.config(state=tk.NORMAL)
chat_area.insert(tk.END, f"You: {user_input}\n\n")
chat_area.config(state=tk.DISABLED)
entry_user.delete(0, tk.END) # Clear input field
# Get API key from user input
api_key = entry_api.get().strip()
if not api_key:
chat_area.config(state=tk.NORMAL)
chat_area.insert(tk.END, "Error: Please enter your OpenAI API key first!\n\n")
chat_area.config(state=tk.DISABLED)
return
# Set OpenAI API key
openai.api_key = api_key
# Add user message to chat history
chat_history.append({"role": "user", "content": user_input})
try:
# Call OpenAI API for response
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Affordable and effective model
messages=chat_history,
temperature=0.7 # Balance between creativity and accuracy
)
# Extract and display AI response
ai_response = response.choices[0].message["content"].strip()
chat_history.append({"role": "assistant", "content": ai_response})
chat_area.config(state=tk.NORMAL)
chat_area.insert(tk.END, f"Assistant: {ai_response}\n\n")
chat_area.config(state=tk.DISABLED)
except Exception as e:
# Handle errors (e.g., invalid key, rate limits)
chat_area.config(state=tk.NORMAL)
chat_area.insert(tk.END, f"Error: {str(e)}\n\n")
chat_area.config(state=tk.DISABLED)
def clear_chat():
"""Reset chat history and clear the chat area."""
global chat_history
chat_history = [{"role": "system", "content": "You are a helpful assistant."}]
chat_area.config(state=tk.NORMAL)
chat_area.delete(1.0, tk.END)
chat_area.config(state=tk.DISABLED)
# Create main window
root = tk.Tk()
root.title("OpenAI Chatbot")
root.geometry("600x500") # Set window size
# API Key Section
frame_api = tk.Frame(root)
label_api = tk.Label(frame_api, text="OpenAI API Key:")
label_api.pack(side=tk.LEFT, padx=5)
entry_api = tk.Entry(frame_api, width=50, show="*") # Hide key for security
entry_api.pack(side=tk.LEFT, padx=5)
frame_api.pack(pady=10)
# Chat Area
chat_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=70, height=20, state=tk.DISABLED)
chat_area.pack(pady=10)
# User Input Section
frame_input = tk.Frame(root)
entry_user = tk.Entry(frame_input, width=50)
entry_user.pack(side=tk.LEFT, padx=5)
btn_send = tk.Button(frame_input, text="Send", command=send_message)
btn_send.pack(side=tk.LEFT, padx=5)
btn_clear = tk.Button(frame_input, text="Clear Chat", command=clear_chat)
btn_clear.pack(side=tk.LEFT, padx=5)
frame_input.pack(pady=10)
# Run the GUI loop
root.mainloop()
How to Use
- Get Your OpenAI API Key: Go to OpenAI Platform and generate a key (you need an account).
- Run the Script: Execute the code. A window will open.
- Enter API Key: Paste your OpenAI API key into the input field labeled "OpenAI API Key".
- Chat: Type your message in the bottom input field and click "Send" to get a response. Use "Clear Chat" to reset the conversation.
Key Features
- Contextual Conversations: Maintains chat history so the AI remembers previous messages.
- Error Handling: Shows errors (e.g., invalid key, no internet) in the chat area.
- Security: Hides the API key (using
show="*"). - User-Friendly: Scrolled chat area, clear input fields, and intuitive buttons.
Notes
- Cost: The script uses
gpt-3.5-turbo, which is cost-effective (about $0.002 per 1k tokens). - Rate Limits: OpenAI has rate limits (e.g., 3 requests per minute for free tiers). If you hit a limit, the error message will inform you.
- Privacy: The chat history is stored only in memory (no persistence). To save conversations, add a "Save" button to write to a file.
This script provides a basic but functional chatbot GUI. You can extend it with features like:
- Custom system prompts (e.g., "You are a coding tutor").
- Dark mode.
- Saving/loading chat history.
- Voice input/output.
Let me know if you need help with any extensions!


作者声明:本文包含人工智能生成内容。