svg-processor/gui/log_frame.py
2025-05-16 18:15:31 +04:00

125 lines
3.7 KiB
Python

import tkinter as tk
from tkinter import ttk, scrolledtext
class LogFrame(ttk.Frame):
"""Frame for displaying log messages."""
def __init__(self, parent, **kwargs):
"""
Initialize the Log Frame.
Args:
parent: The parent widget.
**kwargs: Additional arguments for ttk.Frame.
"""
super().__init__(parent, **kwargs)
self._create_widgets()
def _create_widgets(self):
"""Create the widgets for the log frame."""
# Create scrolled text widget
self.log_text = scrolledtext.ScrolledText(
self,
wrap=tk.WORD,
width=80,
height=20,
font=('Consolas', 10)
)
self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.log_text.configure(state='disabled')
# Create button frame
button_frame = ttk.Frame(self)
button_frame.pack(fill=tk.X, padx=5, pady=(0, 5))
# Create buttons
ttk.Button(
button_frame,
text="Clear",
command=self.clear
).pack(side=tk.LEFT, padx=5)
ttk.Button(
button_frame,
text="Copy to Clipboard",
command=self.copy_to_clipboard
).pack(side=tk.LEFT, padx=5)
ttk.Button(
button_frame,
text="Save to File",
command=self.save_to_file
).pack(side=tk.LEFT, padx=5)
def append(self, text):
"""Append text to the log.
Args:
text (str): The text to append.
"""
self.log_text.configure(state='normal')
self.log_text.insert('end', text)
self.log_text.see('end')
self.log_text.configure(state='disabled')
def clear(self):
"""Clear the log."""
self.log_text.configure(state='normal')
self.log_text.delete(1.0, tk.END)
self.log_text.configure(state='disabled')
def copy_to_clipboard(self):
"""Copy log contents to clipboard."""
self.log_text.configure(state='normal')
text = self.log_text.get(1.0, tk.END)
self.log_text.configure(state='disabled')
if text.strip():
self.clipboard_clear()
self.clipboard_append(text)
self.append("\nCopied to clipboard.\n")
def save_to_file(self):
"""Save log contents to a file."""
self.log_text.configure(state='normal')
text = self.log_text.get(1.0, tk.END)
self.log_text.configure(state='disabled')
if text.strip():
from tkinter import filedialog
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)
if file_path:
try:
with open(file_path, 'w') as f:
f.write(text)
self.append(f"\nLog saved to {file_path}\n")
except Exception as e:
self.append(f"\nError saving log: {str(e)}\n")
# Example usage (for testing)
if __name__ == '__main__':
root = tk.Tk()
root.title("Log Frame Test")
root.geometry("600x400")
# Style for testing
style = ttk.Style()
style.theme_use('clam')
style.configure('TFrame', background='#f0f0f0')
style.configure('TLabel', background='#f0f0f0')
# Create and pack the log frame
log_frame = LogFrame(root)
log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Test buttons
def add_log():
log_frame.append("Test log message\n")
ttk.Button(root, text="Add Log", command=add_log).pack(pady=5)
root.mainloop()