Last active 1739984695

Python simple text edit using Tkinter

simpletextedit.py Raw
1import tkinter as tk
2from tkinter.filedialog import askopenfilename, asksaveasfilename
3
4def open_file():
5 """Open a file for editing."""
6 filepath = askopenfilename(
7 filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
8 )
9 if not filepath:
10 return
11 txt_edit.delete(1.0, tk.END)
12 with open(filepath, "r") as input_file:
13 text = input_file.read()
14 txt_edit.insert(tk.END, text)
15 window.title(f"Zipity - {filepath}")
16
17def save_file():
18 """Save the current file as a new file."""
19 filepath = asksaveasfilename(
20 defaultextension="txt",
21 filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
22 )
23 if not filepath:
24 return
25 with open(filepath, "w") as output_file:
26 text = txt_edit.get(1.0, tk.END)
27 output_file.write(text)
28 window.title(f"Zipity - {filepath}")
29
30window = tk.Tk()
31window.title("Zipity")
32window.rowconfigure(0, minsize=800, weight=1)
33window.columnconfigure(1, minsize=800, weight=1)
34
35txt_edit = tk.Text(window)
36fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
37btn_open = tk.Button(fr_buttons, text="Open", command=open_file)
38btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file)
39
40btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
41btn_save.grid(row=1, column=0, sticky="ew", padx=5)
42
43fr_buttons.grid(row=0, column=0, sticky="ns")
44txt_edit.grid(row=0, column=1, sticky="nsew")
45
46window.mainloop()
47