Python自制文本编辑器。 随便写的半成品
from tkinter import *
from tkinter import filedialog, messagebox
class FindWindow:
def __init__(self, parent):
self.parent = parent
self.find_window = Toplevel(parent)
self.find_window.title("Find")
self.find_window.geometry("300x100")
# 创建查找标签和输入框
self.find_label = Label(self.find_window, text="Find:")
self.find_label.grid(row=0, column=0, padx=5, pady=5)
self.find_entry = Entry(self.find_window)
self.find_entry.grid(row=0, column=1, padx=5, pady=5)
# 创建查找按钮
self.find_button = Button(self.find_window, text="Find", command=self.find_text)
self.find_button.grid(row=0, column=2, padx=5, pady=5)
def find_text(self):
"""Find the specified text in the text area."""
# 获取要查找的文本
search_text = self.find_entry.get()
if search_text:
# 开始查找
start_index = "1.0"
while True:
# 从当前位置开始搜索,直到找到目标文本或搜索到文本末尾
start_index = self.parent.text_area.search(search_text, start_index, stopindex=END)
if not start_index:
# 如果没有找到目标文本,弹出提示框
messagebox.showinfo("Find", "No more occurrences found.")
break
else:
# 如果找到了目标文本,选中它并将焦点设置在找到的文本上
end_index = f"{start_index}+{len(search_text)}c"
self.parent.text_area.tag_add(SEL, start_index, end_index)
self.parent.text_area.mark_set(INSERT, start_index)
self.parent.text_area.see(INSERT)
# 更新起始位置,以便继续搜索下一个目标文本
start_index = end_index
else:
# 如果未输入查找文本,弹出提示框
messagebox.showwarning("Find", "Please enter text to find.")
class Main:
def __init__(self):
self.root = Tk()
self.root.title('TkNotepad - Untitled')
self.root.geometry('720x500')
self.current_file = None
find_window = FindWindow(self)
# 创建菜单栏
menubar = Menu(self.root)
self.root.config(menu=menubar)
# 创建文件菜单
file_menu = Menu(menubar, tearoff=0)
file_menu.add_command(label='New File', accelerator='Ctrl+N', command=self.new_file)
file_menu.add_command(label='Open...', accelerator='Ctrl+O', command=self.open_file)
file_menu.add_command(label='Save', accelerator='Ctrl+S', command=self.save_file)
file_menu.add_command(label='Save As...', accelerator='Ctrl+Shift+S', command=self.save_as_file)
file_menu.add_separator()
file_menu.add_command(label='Close Window', accelerator='Alt+F4')
file_menu.add_command(label='Exit', command=self.root.quit)
menubar.add_cascade(label='File', menu=file_menu)
# 创建编辑菜单
edit_menu = Menu(menubar, tearoff=0)
edit_menu.add_command(label='Undo', accelerator='Ctrl+Z', command=self.undo)
edit_menu.add_command(label='Redo', accelerator='Ctrl+Y', command=self.redo)
edit_menu.add_separator()
edit_menu.add_command(label='Cut', accelerator='Ctrl+X', command=self.cut)
edit_menu.add_command(label='Copy', accelerator='Ctrl+C', command=self.copy)
edit_menu.add_command(label='Paste', accelerator='Ctrl+V', command=self.paste)
edit_menu.add_separator()
edit_menu.add_command(label='Select All', accelerator='Ctrl+A', command=self.select_all)
edit_menu.add_command(label='Select Line', accelerator='Ctrl+L', command=self.select_line)
edit_menu.add_separator()
edit_menu.add_command(label='Find...', accelerator='Ctrl+F', command=find_window.find_window.deiconify)
menubar.add_cascade(label='Edit', menu=edit_menu)
# 创建工具菜单
tool_menu = Menu(menubar, tearoff=0)
tool_menu.add_command(label='Options')
menubar.add_cascade(label='Tools', menu=tool_menu)
# 创建设置菜单
setting_menu = Menu(menubar, tearoff=0)
setting_menu.add_command(label='Language')
menubar.add_cascade(label='Setting', menu=setting_menu)
# 创建帮助菜单
help_menu = Menu(menubar, tearoff=0)
help_menu.add_command(label='Docs')
help_menu.add_command(label='About TkNotepad')
menubar.add_cascade(label='Help', menu=help_menu)
# 创建文本区域
self.text_area = Text(self.root, wrap='word', undo=True, font=('Arial', 11))
self.text_area.pack(expand=True, fill='both')
# 创建垂直滚动条
scrollbar = Scrollbar(self.text_area, command=self.text_area.yview)
scrollbar.pack(side='right', fill='y')
self.text_area.config(yscrollcommand=scrollbar.set)
# 创建状态栏
self.status_bar = Label(self.root, text='Ln: 1, Col: 1', bd=1, relief='sunken', anchor='e')
self.status_bar.pack(side='bottom', fill='x')
# 绑定事件,当光标位置变化时更新状态栏显示
self.text_area.bind('<KeyRelease>', self.update_status_bar)
self.text_area.bind('<ButtonRelease>', self.update_status_bar)
self.text_area.bind('<Motion>', self.update_status_bar)
self.root.mainloop()
def new_file(self):
"""Create a new file."""
if self.is_new_file_modified():
# Prompt a message box if the text area contains content for a new file
response = messagebox.askyesno("Unsaved Changes",
"You have unsaved changes. Are you sure you want to create a new file?")
if response:
self.text_area.delete('1.0', END)
self.current_file = None
self.update_status_bar(None)
self.update_window_title()
else:
self.text_area.delete('1.0', END)
self.current_file = None
self.update_status_bar(None)
self.update_window_title()
def open_file(self):
"""Open an existing file."""
def open_file_handler(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
self.text_area.delete('1.0', END)
self.text_area.insert('1.0', file.read())
self.current_file = file_path
self.update_status_bar(None)
self.update_window_title()
except Exception as e:
# Modified messagebox error display
messagebox.showerror("Error", f"Failed to open file: {file_path}\nError: {e}")
if self.is_file_modified():
response = messagebox.askyesno("Unsaved Changes",
"You have unsaved changes. Are you sure you want to open a new file?")
if not response:
return
file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
open_file_handler(file_path)
def save_file(self):
"""Save the current file."""
if self.current_file:
with open(self.current_file, 'w', encoding='utf-8') as file:
file.write(self.text_area.get('1.0', END))
self.update_window_title()
else:
self.save_as_file()
def save_as_file(self):
"""Save the current file as a new file."""
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(self.text_area.get('1.0', END))
self.current_file = file_path
self.update_window_title()
def update_window_title(self):
"""Update window title with file path."""
if self.current_file:
self.root.title(f'TkNotepad - {self.current_file}')
else:
self.root.title('TkNotepad - Untitled')
def is_file_modified(self):
"""
Check if the current file has been modified.
"""
if not self.current_file:
return False
with open(self.current_file, 'r', encoding='utf-8') as file:
return file.read() != self.text_area.get('1.0', 'end-1c')
def is_new_file_modified(self):
"""
Check if the text area contains content for a new file.
"""
return bool(self.text_area.get('1.0', 'end-1c'))
def update_status_bar(self, event):
"""Update status bar with cursor position."""
row, col = self.text_area.index('end-1c').split('.')
self.status_bar.config(text=f'Ln: {row}, Col: {col}')
def undo(self, event=None):
"""Undo the last action."""
try:
self.text_area.edit_undo()
except TclError:
pass
def redo(self, event=None):
"""Redo the last undone action."""
try:
self.text_area.edit_redo()
except TclError:
pass
def cut(self, event=None):
"""Cut selected text."""
self.text_area.event_generate("<<Cut>>")
def copy(self, event=None):
"""Copy selected text."""
self.text_area.event_generate("<<Copy>>")
def paste(self, event=None):
"""Paste text from clipboard."""
self.text_area.event_generate("<<Paste>>")
def select_all(self, event=None):
"""Select all text."""
self.text_area.tag_add('sel', '1.0', 'end')
def select_line(self, event=None):
"""Select the current line."""
self.text_area.tag_add('sel', 'insert linestart', 'insert lineend+1c')
if __name__ == "__main__":
Main()