Creating an advanced notepad app using the customtkinter library involves building on the standard tkinter functionality with additional custom styling and functionalities. You would need to install customtkinter first, ensure it's compatible with your Python version, and then use it to enhance the user interface typically available in a GUI application.
Below is a basic example of how you might begin to build an advanced notepad application using customtkinter. This example sets up a window with a menu bar and text editing capabilities.
Installation
First, make sure you have customtkinter installed. You can install it via pip:
bash
pip install customtkinter
Code Example
python
User
add a code line numbers on left side
Assistant
User
your code have some errors, please fix it: Traceback (most recent call last):
File "e:\Mariusz\Programowanie\Lazaro System\Web Info\phone.py", line 107, in
app = AdvancedNotepadApp(root)
^^^^^^^^^^^^^^^^^^^^^^^^
File "e:\Mariusz\Programowanie\Lazaro System\Web Info\phone.py", line 30, in init
self.scrollbar.pack(side='right', fill='y')
File "C:\Users\makij\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 2467, in pack_configure
self.tk.call(
_tkinter.TclError: cannot use geometry manager pack inside .!ctkframe.!ctktextbox2 which already has slaves managed by grid
Assistant
User
include clicking the spacebar when adding lines and add mechanics so that they scroll flush with the written text, instead of config, use configure to avoid errors
Assistant
User
but still if i press Enter that new line doesn't write !!! fix it!
Assistant
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
class AdvancedNotepadApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Notepad")
self.root.geometry("800x600")
# Configure root window with custom styles
ctk.set_appearance_mode("dark") # Modes: "System" (default), "Dark", "Light"
ctk.set_default_color_theme("blue") # Themes: "blue" (default), "green", "dark-blue"
# Create the main text area
self.text_area = ctk.CTkTextbox(master=self.root, wrap="word")
self.text_area.pack(expand=True, fill='both', padx=10, pady=10)
# Initialize menu
self.init_menu()
def init_menu(self):
menu_bar = tk.Menu(self.root)
# File Menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_command(label="Save As", command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
# Edit Menu
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate('<<Cut>>'))
edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate('<<Copy>>'))
edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate('<<Paste>>'))
menu_bar.add_cascade(label="Edit", menu=edit_menu)
self.root.config(menu=menu_bar)
def new_file(self):
self.text_area.delete('1.0', tk.END)
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'r') as file:
self.text_area.delete('1.0', tk.END)
self.text_area.insert(tk.END, file.read())
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'w') as file:
file.write(self.text_area.get('1.0', tk.END))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_as_file(self):
self.save_file()
if __name__ == "__main__":
root = ctk.CTk()
app = AdvancedNotepadApp(root)
root.mainloop()
Explanation
CustomTkinter Setup: The application window is created using customtkinter, which allows for enhanced UI styling compared to standard tkinter.
Appearance Mode and Color Theme: The appearance (dark mode) and theme system (blue theme) are demonstrated to customize the overall look of the application.
Text Area: A CTkTextbox is used to create a scrollable text area for editing documents.
Menu Options: A menu bar is initialized with basic file operations like 'New', 'Open', 'Save', and 'Exit', along with basic edit operations like 'Cut', 'Copy', and 'Paste'.
File Handling: Simple file dialogs are used for opening and saving files.
This application can be further expanded with additional features like search/replace functionality, spell check, text formatting, etc. The use of customtkinter allows for more advanced customization and styling than standard tkinter.
Adding line numbers to a text editor requires creating a line number widget that dynamically adjusts as the user types, inserts, or deletes lines. This can be achieved by creating a tk.Text widget for line numbers and synchronizing it with the main text area. Below is a complete example of the advanced notepad application, modified to include a line number feature.
Full Code with Line Numbers
python
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import customtkinter as ctk
class AdvancedNotepadApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Notepad")
self.root.geometry("800x600")
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Frame for line numbers and text area
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(expand=True, fill='both')
# Line numbers text area (non-editable)
self.line_numbers = ctk.CTkTextbox(self.main_frame, width=40, state='disabled')
self.line_numbers.pack(side='left', fill='y')
# Create the main text area
self.text_area = ctk.CTkTextbox(self.main_frame, wrap="word")
self.text_area.pack(expand=True, fill='both')
self.text_area.bind('<KeyPress>', self.update_line_numbers)
self.text_area.bind('<MouseWheel>', self.update_line_numbers) # Optional: Update on scroll
# Add Scrollbar
self.scrollbar = tk.Scrollbar(self.text_area, orient='vertical', command=self.sync_scroll)
self.scrollbar.pack(side='right', fill='y')
self.text_area.config(yscrollcommand=self.scrollbar.set)
# Initialize menu
self.init_menu()
def init_menu(self):
menu_bar = tk.Menu(self.root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_command(label="Save As", command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate('<<Cut>>'))
edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate('<<Copy>>'))
edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate('<<Paste>>'))
menu_bar.add_cascade(label="Edit", menu=edit_menu)
self.root.config(menu=menu_bar)
def update_line_numbers(self, event=None):
# Allow Tk to process event first.
self.root.after_idle(self._update_line_numbers)
def _update_line_numbers(self):
lines = self.text_area.get("1.0", tk.END).split('\n')
line_numbers_str = "\n".join(str(i + 1) for i, _ in enumerate(lines) if _)
# Update line numbers
self.line_numbers.config(state='normal')
self.line_numbers.delete("1.0", tk.END)
self.line_numbers.insert(tk.END, line_numbers_str)
self.line_numbers.config(state='disabled')
def sync_scroll(self, *args):
self.text_area.yview(*args)
self.line_numbers.yview(*args)
def new_file(self):
self.text_area.delete('1.0', tk.END)
self.update_line_numbers()
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'r') as file:
self.text_area.delete('1.0', tk.END)
self.text_area.insert(tk.END, file.read())
self.update_line_numbers()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'w') as file:
file.write(self.text_area.get('1.0', tk.END))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_as_file(self):
self.save_file()
if __name__ == "__main__":
root = ctk.CTk()
app = AdvancedNotepadApp(root)
root.mainloop()
Key Components Explained
Line Numbers:
The line numbers are managed by a CTkTextbox set to state='disabled' to prevent user editing.
The update_line_numbers method calculates current line numbers and updates the line number widget accordingly.
Synchronization:
The text area and line number area are synchronized using scrollcommand and custom scroll handlers to ensure they scroll together.
Events:
Line numbers update on key presses and optional mouse scrolling by binding these events to the main text area's actions.
This basic implementation allows for improved functionality with line numbers added to the text editor interface. Further functionality, such as syntax highlighting, could be added for more advanced needs.
The error you're encountering is caused by using a mix of the pack and grid geometry managers within the same container. When working with tkinter widgets, it's important to use only one geometry manager within a given parent widget.
To resolve the issue, we need to ensure consistent use of either pack or grid for widgets within the same container. Let's update the layout in the AdvancedNotepadApp class to use the grid geometry manager consistently.
Here's the corrected version of the code:
python
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
class AdvancedNotepadApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Notepad")
self.root.geometry("800x600")
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Frame for line numbers and text area
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(expand=True, fill='both')
# Line numbers text area (non-editable)
self.line_numbers = ctk.CTkTextbox(self.main_frame, width=40, state='disabled', wrap='none')
self.line_numbers.grid(row=0, column=0, sticky='ns')
# Create the main text area
self.text_area = ctk.CTkTextbox(self.main_frame, wrap="word")
self.text_area.grid(row=0, column=1, sticky='nsew')
self.text_area.bind('<KeyPress>', self.update_line_numbers)
self.text_area.bind('<MouseWheel>', self.update_line_numbers)
# Add a vertical scrollbar
self.scrollbar = tk.Scrollbar(self.main_frame, orient='vertical', command=self.sync_scroll)
self.scrollbar.grid(row=0, column=2, sticky='ns')
self.text_area.config(yscrollcommand=self.scrollbar.set)
# Configure grid weights for proper resizing
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(1, weight=1)
# Initialize menu
self.init_menu()
def init_menu(self):
menu_bar = tk.Menu(self.root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_command(label="Save As", command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate('<<Cut>>'))
edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate('<<Copy>>'))
edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate('<<Paste>>'))
menu_bar.add_cascade(label="Edit", menu=edit_menu)
self.root.config(menu=menu_bar)
def update_line_numbers(self, event=None):
self.root.after_idle(self._update_line_numbers)
def _update_line_numbers(self):
lines = self.text_area.get("1.0", tk.END).split('\n')
line_numbers_str = "\n".join(str(i + 1) for i, _ in enumerate(lines) if _)
self.line_numbers.config(state='normal')
self.line_numbers.delete("1.0", tk.END)
self.line_numbers.insert(tk.END, line_numbers_str)
self.line_numbers.config(state='disabled')
def sync_scroll(self, *args):
self.text_area.yview(*args)
self.line_numbers.yview(*args)
def new_file(self):
self.text_area.delete('1.0', tk.END)
self.update_line_numbers()
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'r') as file:
self.text_area.delete('1.0', tk.END)
self.text_area.insert(tk.END, file.read())
self.update_line_numbers()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'w') as file:
file.write(self.text_area.get('1.0', tk.END))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_as_file(self):
self.save_file()
if __name__ == "__main__":
root = ctk.CTk()
app = AdvancedNotepadApp(root)
root.mainloop()
Key Changes
Grid Manager Consistency: The grid geometry manager is used for all components (line_numbers, text_area, and scrollbar) within the main_frame.
Grid Weight Configuration: This ensures that the text area expands properly as the window resizes.
Scrollbar: The scrollbar is included in the grid setup and attached to both the text area and line number area for synchronized scrolling.
These changes should resolve the geometry manager conflict and ensure consistent layout behavior.
To address the concerns you've raised, we will make sure the line numbers update every time the spacebar is pressed, not just with regular keypresses, and that they scroll in line with the main text area. We'll also adjust the code to use configure instead of config, which is an alias but sometimes preferred for clarity. Here's how you can achieve this:
Complete Code with Enhancements
python
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
class AdvancedNotepadApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Notepad")
self.root.geometry("800x600")
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Frame for line numbers and text area
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(expand=True, fill='both')
# Line numbers text area (non-editable)
self.line_numbers = ctk.CTkTextbox(self.main_frame, width=40, state='disabled', wrap='none')
self.line_numbers.grid(row=0, column=0, sticky='ns')
# Create the main text area
self.text_area = ctk.CTkTextbox(self.main_frame, wrap="word")
self.text_area.grid(row=0, column=1, sticky='nsew')
self.text_area.bind('<KeyPress>', self.update_line_numbers_on_key)
self.text_area.bind('<Return>', self.update_line_numbers_on_key)
self.text_area.bind('<space>', self.update_line_numbers_on_key)
self.text_area.bind('<Button-1>', self.update_line_numbers_on_click)
# Add a vertical scrollbar
self.scrollbar = tk.Scrollbar(self.main_frame, orient='vertical', command=self.sync_scroll)
self.scrollbar.grid(row=0, column=2, sticky='ns')
self.text_area.configure(yscrollcommand=self.scrollbar.set)
# Configure grid weights for proper resizing
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(1, weight=1)
# Initialize menu
self.init_menu()
def init_menu(self):
menu_bar = tk.Menu(self.root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_command(label="Save As", command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate('<<Cut>>'))
edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate('<<Copy>>'))
edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate('<<Paste>>'))
menu_bar.add_cascade(label="Edit", menu=edit_menu)
self.root.config(menu=menu_bar)
def update_line_numbers_on_key(self, event=None):
self.root.after_idle(self._update_line_numbers)
def update_line_numbers_on_click(self, event=None):
self.root.after(1, self._update_line_numbers)
def _update_line_numbers(self):
lines = self.text_area.get("1.0", tk.END).split('\n')
line_numbers_str = "\n".join(str(i + 1) for i, _ in enumerate(lines) if _)
self.line_numbers.configure(state='normal')
self.line_numbers.delete("1.0", tk.END)
self.line_numbers.insert(tk.END, line_numbers_str)
self.line_numbers.configure(state='disabled')
# Sync scroll
self.line_numbers.yview_moveto(self.text_area.yview()[0])
def sync_scroll(self, *args):
self.text_area.yview(*args)
self.line_numbers.yview(*args)
def new_file(self):
self.text_area.delete('1.0', tk.END)
self.update_line_numbers_on_key()
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'r') as file:
self.text_area.delete('1.0', tk.END)
self.text_area.insert(tk.END, file.read())
self.update_line_numbers_on_key()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'w') as file:
file.write(self.text_area.get('1.0', tk.END))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_as_file(self):
self.save_file()
if __name__ == "__main__":
root = ctk.CTk()
app = AdvancedNotepadApp(root)
root.mainloop()
Key Changes and Enhancements
Spacebar Handling: The '<space>' event is added to update line numbers when pressing the spacebar, allowing updates with white spaces.
Line Number Updates: The _update_line_numbers method is adjusted to also handle vertical syncing between the line number area and the text area using yview_moveto.
Consistent Naming for Configuration: Changed to use configure instead of config to modify widget properties, which is more explicit and often recommended in larger projects.
Flushed Scrolling: The use of yview_moveto ensures that the line numbers scroll in sync with the text, making sure they match accurately with the corresponding text lines.
This setup should meet your needs for an advanced notepad with line numbers that update dynamically, using more structured and reliable code practices.
To ensure that the line numbers update correctly when the Enter key is pressed, we need to make sure the update function is triggered appropriately. The issue might be related to the event binding, particularly with the <KeyPress> event not catching Enter key presses. Instead, we can use <KeyRelease> to ensure it captures all keys including Enter. Let’s update the implementation to address this:
Here's the corrected version:
python
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
class AdvancedNotepadApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Notepad")
self.root.geometry("800x600")
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Frame for line numbers and text area
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(expand=True, fill='both')
# Line numbers text area (non-editable)
self.line_numbers = ctk.CTkTextbox(self.main_frame, width=40, state='disabled', wrap='none')
self.line_numbers.grid(row=0, column=0, sticky='ns')
# Create the main text area
self.text_area = ctk.CTkTextbox(self.main_frame, wrap="word")
self.text_area.grid(row=0, column=1, sticky='nsew')
self.text_area.bind('<KeyRelease>', self.update_line_numbers) # Use KeyRelease
self.text_area.bind('<Button-1>', self.update_line_numbers_on_click)
# Add a vertical scrollbar
self.scrollbar = tk.Scrollbar(self.main_frame, orient='vertical', command=self.sync_scroll)
self.scrollbar.grid(row=0, column=2, sticky='ns')
self.text_area.configure(yscrollcommand=self.scrollbar.set)
# Configure grid weights for proper resizing
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(1, weight=1)
# Initialize menu
self.init_menu()
def init_menu(self):
menu_bar = tk.Menu(self.root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_command(label="Save As", command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate('<<Cut>>'))
edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate('<<Copy>>'))
edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate('<<Paste>>'))
menu_bar.add_cascade(label="Edit", menu=edit_menu)
self.root.configure(menu=menu_bar)
def update_line_numbers(self, event=None):
self.root.after_idle(self._update_line_numbers)
def update_line_numbers_on_click(self, event=None):
self.root.after(1, self._update_line_numbers)
def _update_line_numbers(self):
lines = self.text_area.get("1.0", tk.END).split('\n')
line_numbers_str = "\n".join(str(i + 1) for i, _ in enumerate(lines) if _ or i == len(lines) - 1)
self.line_numbers.configure(state='normal')
self.line_numbers.delete("1.0", tk.END)
self.line_numbers.insert(tk.END, line_numbers_str)
self.line_numbers.configure(state='disabled')
# Sync scroll
self.line_numbers.yview_moveto(self.text_area.yview()[0])
def sync_scroll(self, *args):
self.text_area.yview(*args)
self.line_numbers.yview(*args)
def new_file(self):
self.text_area.delete('1.0', tk.END)
self.update_line_numbers()
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'r') as file:
self.text_area.delete('1.0', tk.END)
self.text_area.insert(tk.END, file.read())
self.update_line_numbers()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
try:
with open(file_path, 'w') as file:
file.write(self.text_area.get('1.0', tk.END))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def save_as_file(self):
self.save_file()
if __name__ == "__main__":
root = ctk.CTk()
app = AdvancedNotepadApp(root)
root.mainloop()
Key Changes
KeyRelease Binding: Changed the event binding from <KeyPress> to <KeyRelease> to ensure we capture Enter key releases. This captures the exact moment lines are added, including spaces and new lines from pressing Enter.
Line Number Calculation: Modified the line number logic to ensure it accounts for the last empty line commonly present after pressing Enter.
These changes should ensure that the line number update mechanism works seamlessly when new lines are added via the Enter key.