Skip to content

Instantly share code, notes, and snippets.

@anton-petrov
Created November 23, 2021 14:23
Show Gist options
  • Save anton-petrov/b7942b5cbf4da9d229de5c06c4a80aab to your computer and use it in GitHub Desktop.
Save anton-petrov/b7942b5cbf4da9d229de5c06c4a80aab to your computer and use it in GitHub Desktop.
Текстовый редактор на Tkinter
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def open_file():
filepath = askopenfilename(
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if not filepath:
return
txt_edit.delete(1.0, tk.END)
with open(filepath, "r", encoding="utf-8",) as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f"Простой текстовый редактор - {filepath}")
def save_file():
filepath = asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if not filepath:
return
with open(filepath, "w", encoding="utf-8") as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f"Простой текстовый редактор - {filepath}")
window = tk.Tk()
window.title("Простой текстовый редактор")
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)
txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Открыть", command=open_file)
btn_save = tk.Button(fr_buttons, text="Сохранить как...", command=save_file)
btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)
fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")
window.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment