I have created an application in Python for creating and reading text files. I would like to share the outcome of this effort with you.
The created application is as follows
At the time of program execution
Overview of Functions
"I had ChatGPT explain the functionality.
-
The TextEditor class is derived from ttk.Frame and represents the main window of the text editor application.
-
It initializes the window, sets up the layout, creates various widget elements such as text boxes, entry fields for file names, buttons for opening and saving files, and more.
-
The open_file method uses the askopenfilename dialog to open a file, read its content, and display it in the text box.
-
The save_file method uses the asksaveasfilename dialog to save the content of the text box to a file.
-
The Messagebox class is used to display a message box with a custom title and button style.
-
The application is executed by creating a ttk.Window object. The title is set to 'Text Editor' and the theme is set to 'minty'. An instance of the TextEditor class is instantiated within this window."
ソースコード
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.scrolledtext import ScrolledText
from ttkbootstrap.dialogs import Messagebox
class TextEditor(ttk.Frame):
def __init__(self, master):
super().__init__(master, padding=15)
self.filename = ttk.StringVar()
self.pack(fill=BOTH, expand=YES)
self.create_widget_elements()
def create_widget_elements(self):
style = ttk.Style()
self.textbox = ScrolledText(
master=self,
highlightcolor=style.colors.success,
highlightbackground=style.colors.border,
highlightthickness=1
)
self.textbox.pack(fill=BOTH, expand=YES)
file_entry = ttk.Entry(self, textvariable=self.filename)
file_entry.pack(side=LEFT, fill=X, expand=YES, padx=(0, 5), pady=10)
open_btn = ttk.Button(self, text='開く', command=self.open_file, bootstyle= 'warning')
open_btn.pack(side=LEFT, fill=X, padx=(5, 0), pady=10)
save_btn = ttk.Button(self, text='保存', command=self.save_file, bootstyle= 'success')
save_btn.pack(side=RIGHT, fill=X, padx=(0, 5), pady=10)
def open_file(self):
path = askopenfilename()
if not path:
return
with open(path, encoding='utf-8') as f:
self.textbox.delete('1.0', END)
self.textbox.insert(END, f.read())
self.filename.set(path)
def save_file(self):
mb = Messagebox.okcancel("ファイルを保存しますか?")
if mb == 'OK':
path = asksaveasfilename(defaultextension='.txt') # テキストファイルを保存する。
if not path:
return
with open(path, 'w', encoding='utf-8') as f:
f.write(self.textbox.get('1.0', END))
self.filename.set(path)
else:
return
Messagebox.ok("ファイルを保存しました。")
if __name__ == '__main__':
app = ttk.Window("Text Editor", "minty")
TextEditor(app)
app.mainloop()