Certainly! Enhancing the visual appeal of your Tkinter GUI can significantly improve user experience. Below is an upgraded version of your GUI with the following enhancements:
- Modern Theme: Switched to the
ttkbootstrap package, which offers modern and customizable themes.
- Improved Layout: Added padding and spacing for better organization.
- Enhanced Widgets: Updated fonts, colors, and added icons to buttons for a more intuitive interface.
- Responsive Design: Ensured that the layout adjusts gracefully when resizing the window.
- Message Bubbles: Styled chat messages as message bubbles with distinct colors for user and bot messages.
Step 1: Install ttkbootstrap
First, install the ttkbootstrap package, which provides a variety of modern themes for Tkinter:
pip install ttkbootstrap
Step 2: Revised GUI Code
Here's the revised code incorporating the enhancements:
import tkinter as tk
from tkinter import ttk, scrolledtext
from ttkbootstrap import Style
from ttkbootstrap.constants import *
from gradio_client import Client
import re
import uuid
import subprocess
import os
# Initialize Gradio Client
client = Client("yuntian-deng/o1mini")
MAX_RETRIES = 5
# Function to extract Python code blocks from response
def extract_code(response):
code_pattern = re.compile(r'```python\s*\n(.*?)```', re.DOTALL)
codes = code_pattern.findall(response)
return codes
# Function to save code to a uniquely named file
def save_code(code):
unique_id = uuid.uuid4().hex
filename = f"script_{unique_id}.py"
with open(filename, 'w', encoding='utf-8') as file:
file.write(code)
return filename
# Function to execute the saved Python script
def execute_code(filename):
try:
result = subprocess.run(
['python', filename],
capture_output=True,
text=True,
check=True
)
return True, result.stdout
except subprocess.CalledProcessError as e:
return False, e.stderr
# Function to fix code using the chatbot
def fix_code(original_code, error_message):
prompt = (
f"An error occurred:\n{error_message}\n\n"
f"Please provide a corrected script."
)
fixed_code = client.predict(
inputs=prompt,
top_p=1.0,
temperature=1.0,
chat_counter=0.0,
chatbot=[],
api_name="/predict"
)
return fixed_code[0] # Assuming the response is the corrected code
# Function to process code with retries
def process_code(initial_code):
current_code = initial_code
for attempt in range(1, MAX_RETRIES + 1):
filename = save_code(current_code)
success, output = execute_code(filename)
os.remove(filename)
if success:
chatbox.configure(state='normal')
chatbox.insert(tk.END, f"[Execution Success]:\n{output}\n", "success")
chatbox.configure(state='disabled')
status_var.set("Script executed successfully.")
return
else:
chatbox.configure(state='normal')
chatbox.insert(tk.END, f"[Error Attempt {attempt}]:\n{output}\n", "error")
chatbox.configure(state='disabled')
status_var.set(f"Error on attempt {attempt}.")
if attempt < MAX_RETRIES:
chatbox.configure(state='normal')
chatbox.insert(tk.END, "Attempting to fix the error...\n", "info")
chatbox.configure(state='disabled')
current_code = fix_code(current_code, output)
else:
chatbox.configure(state='normal')
chatbox.insert(tk.END, "Max retries reached. Manual check required.\n", "error")
chatbox.configure(state='disabled')
status_var.set("Max retries reached. Manual intervention needed.")
return
# Function to handle sending messages
def send_message():
user_input = input_text.get()
if not user_input.strip():
status_var.set("Please enter a message to send.")
return
chatbox.configure(state='normal')
chatbox.insert(tk.END, f"User: {user_input}\n", "user")
chatbox.configure(state='disabled')
status_var.set("Sending message...")
root.update_idletasks()
result = client.predict(
inputs=user_input,
top_p=1.0,
temperature=1.0,
chat_counter=0.0,
chatbot=[],
api_name="/predict"
)
display_result(result)
bot_response = result[0]
codes = extract_code(bot_response)
if codes:
for code in codes:
process_code(code)
else:
chatbox.configure(state='normal')
chatbox.insert(tk.END, "Bot: No Python code detected in the response.\n", "info")
chatbox.configure(state='disabled')
status_var.set("Message sent.")
# Function to reset the textbox
def reset_textbox():
result = client.predict(api_name="/reset_textbox")
input_text.set("")
chatbox.configure(state='normal')
chatbox.insert(tk.END, f"System: {result}\n", "system")
chatbox.configure(state='disabled')
status_var.set("Textbox reset.")
# Function to enable inputs
def enable_inputs():
result = client.predict(api_name="/enable_inputs")
chatbox.configure(state='normal')
chatbox.insert(tk.END, "System: Inputs enabled.\n", "system")
chatbox.configure(state='disabled')
status_var.set("Inputs enabled.")
# Function to display results in the chatbox
def display_result(result):
bot_response, chat_counter, status_code, textbox_response = result
chatbox.configure(state='normal')
chatbox.insert(tk.END, f"Bot: {bot_response}\n", "bot")
chatbox.insert(tk.END, f"Status: {status_code}\n\n", "status")
chatbox.configure(state='disabled')
input_text.set("")
# Initialize Tkinter root window with ttkbootstrap Style
style = Style(theme='flatly') # You can choose other themes like 'cyborg', 'superhero', etc.
root = style.master
root.title("Chatbot Interface with Python Script Executor")
root.geometry("900x600")
root.minsize(700, 500)
# Configure grid layout
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
# Main frame
main_frame = ttk.Frame(root, padding="20 20 20 20")
main_frame.grid(row=0, column=0, sticky='NSEW')
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
# Chatbox Label
chat_label = ttk.Label(main_frame, text="Chat History", font=("Helvetica", 14, "bold"), anchor="w")
chat_label.grid(row=0, column=0, sticky='W')
# Chatbox ScrolledText with enhanced styling
chatbox = scrolledtext.ScrolledText(main_frame, wrap=tk.WORD, state='disabled', font=("Helvetica", 11),
bg="#f0f0f0", fg="#333333", relief="flat")
chatbox.grid(row=1, column=0, columnspan=3, sticky='NSEW', pady=(10, 10))
chatbox.tag_configure("user", foreground="#1E90FF", font=("Helvetica", 11, "bold"))
chatbox.tag_configure("bot", foreground="#32CD32", font=("Helvetica", 11, "bold"))
chatbox.tag_configure("system", foreground="#9932CC", font=("Helvetica", 11, "italic"))
chatbox.tag_configure("error", foreground="#FF4500", font=("Helvetica", 11, "bold"))
chatbox.tag_configure("success", foreground="#228B22", font=("Helvetica", 11, "bold"))
chatbox.tag_configure("info", foreground="#FF8C00", font=("Helvetica", 11, "italic"))
chatbox.tag_configure("status", foreground="#696969", font=("Helvetica", 10, "italic"))
# Input Frame
input_frame = ttk.Frame(main_frame)
input_frame.grid(row=2, column=0, columnspan=3, sticky='EW', pady=(10, 10))
input_frame.columnconfigure(0, weight=1)
input_frame.columnconfigure(1, weight=0)
# Input Label
input_label = ttk.Label(input_frame, text="Your Message:", font=("Helvetica", 12))
input_label.grid(row=0, column=0, sticky='W', padx=(0, 5))
# Input Entry
input_text = tk.StringVar()
entry = ttk.Entry(input_frame, textvariable=input_text, font=("Helvetica", 12))
entry.grid(row=1, column=0, sticky='EW', padx=(0, 10), pady=(5, 0))
entry.focus()
# Button Frame
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=3, column=0, sticky='EW', pady=(10, 0))
button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, weight=1)
button_frame.columnconfigure(2, weight=1)
# Send Button with icon
send_icon = tk.PhotoImage(file="send_icon.png") # Ensure you have a 'send_icon.png' in your directory
send_button = ttk.Button(button_frame, text="Send", command=send_message, compound=LEFT, image=send_icon)
send_button.grid(row=0, column=0, padx=5, ipadx=10, sticky='EW')
# Reset Textbox Button with icon
reset_icon = tk.PhotoImage(file="reset_icon.png") # Ensure you have a 'reset_icon.png' in your directory
reset_button = ttk.Button(button_frame, text="Reset Textbox", command=reset_textbox, compound=LEFT, image=reset_icon)
reset_button.grid(row=0, column=1, padx=5, ipadx=10, sticky='EW')
# Enable Inputs Button with icon
enable_icon = tk.PhotoImage(file="enable_icon.png") # Ensure you have a 'enable_icon.png' in your directory
enable_button = ttk.Button(button_frame, text="Enable Inputs", command=enable_inputs, compound=LEFT, image=enable_icon)
enable_button.grid(row=0, column=2, padx=5, ipadx=10, sticky='EW')
# Status Bar
status_var = tk.StringVar()
status_var.set("Welcome! Ready to chat.")
status_bar = ttk.Label(root, textvariable=status_var, relief='sunken', anchor='w', font=("Helvetica", 10))
status_bar.grid(row=1, column=0, sticky='EW')
# Make the chatbox expandable
main_frame.rowconfigure(1, weight=1)
main_frame.columnconfigure(0, weight=1)
# Bind Enter key to send message
root.bind('<Return>', lambda event: send_message())
# Start the Tkinter event loop
root.mainloop()
Step 3: Adding Icons (Optional)
To further enhance the visuals, you can add icons to the buttons. Here's how:
-
Choose Icons: Select appropriate PNG icons for the "Send", "Reset Textbox", and "Enable Inputs" buttons. Name them send_icon.png, reset_icon.png, and enable_icon.png respectively.
-
Place Icons: Ensure these icon files are in the same directory as your Python script.
-
Load Icons: The revised code includes placeholders for loading these icons. If you prefer not to use icons, you can remove the image and compound parameters from the ttk.Button widgets.
Step 4: Explanation of Enhancements
-
ttkbootstrap Integration:
- Modern Themes:
ttkbootstrap provides themes like 'flatly', 'cyborg', 'superhero', etc., which give your application a modern look.
- Consistent Styling: Ensures that all widgets have a consistent and appealing style.
-
Layout Improvements:
- Padding and Margins: Increased padding around frames and widgets for better spacing.
- Responsive Grid: Configured grid weights so that widgets resize gracefully when the window size changes.
-
Enhanced Chatbox:
- Background and Foreground Colors: Set a light background with darker text for better readability.
- Font Styling: Used different font styles (bold, italic) and colors to distinguish between user messages, bot responses, system messages, errors, and informational texts.
- Scrollable Area: Ensured the chatbox is scrollable to handle extended conversations.
-
Input Area:
- Labels and Entry: Clear labels and a sizable entry box for user input.
- Focus: Automatically focuses on the input field for quicker typing.
-
Buttons with Icons:
- Visual Cues: Buttons now include icons that provide visual cues about their functionality.
- Consistent Size: Buttons are uniformly sized and spaced.
-
Status Bar:
- Feedback: Provides real-time feedback to the user about the application's state.
- Discreet Placement: Located at the bottom, it doesn't interfere with the main content.
Step 5: Running the Application
Ensure you have all the necessary icons in place (if you choose to use them) and then run your Python script. The GUI should now have a more modern and polished appearance, enhancing the overall user experience.
Additional Tips
- Customization: Feel free to experiment with different themes available in
ttkbootstrap to find one that best suits your preferences.
- Icons: If you don't have specific icons, you can download free icons from websites like Flaticon or Icons8.
- Error Handling: Consider adding more robust error handling for scenarios like missing icon files.
By implementing these enhancements, your GUI will not only look better but also provide a more intuitive and pleasant experience for users.