Advertisement
here2share

# Tk_Text_Editor.py

Jan 9th, 2022
1,416
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.37 KB | None | 1 0
  1. # Tk_Text_Editor.py
  2.  
  3. import os
  4. import tkinter
  5. import tkinter.colorchooser
  6. from tkinter import ttk, filedialog, TclError
  7. from tkinter.scrolledtext import ScrolledText
  8. from tkinter.font import Font, families
  9.  
  10. class Application(tkinter.Tk):
  11.     def __init__(self):
  12.         """Initialize widgets, methods."""
  13.  
  14.         tkinter.Tk.__init__(self)
  15.         self.grid()
  16.  
  17.         fontoptions = families(self)
  18.         font = Font(family="Verdana", size=10)
  19.  
  20.         menubar = tkinter.Menu(self)
  21.         fileMenu = tkinter.Menu(menubar, tearoff=0)
  22.         editMenu = tkinter.Menu(menubar, tearoff=0)
  23.         fsubmenu = tkinter.Menu(editMenu, tearoff=0)
  24.         ssubmenu = tkinter.Menu(editMenu, tearoff=0)
  25.  
  26.         # adds fonts to the font submenu and associates lambda functions
  27.         for option in fontoptions:
  28.             fsubmenu.add_command(label=option, command = lambda: font.configure(family=option))
  29.         # adds values to the size submenu and associates lambda functions
  30.         for value in range(1,31):
  31.             ssubmenu.add_command(label=str(value), command = lambda: font.configure(size=value))
  32.  
  33.         # adds commands to the menus
  34.         menubar.add_cascade(label="File",underline=0, menu=fileMenu)
  35.         menubar.add_cascade(label="Edit",underline=0, menu=editMenu)
  36.         fileMenu.add_command(label="New", underline=1,
  37.                              command=self.new, accelerator="Ctrl+N")
  38.         fileMenu.add_command(label="Open", command=self.open, accelerator="Ctrl+O")
  39.         fileMenu.add_command(label="Save", command=self.save, accelerator="Ctrl+S")
  40.         fileMenu.add_command(label="Exit", underline=1,
  41.                              command=exit, accelerator="Ctrl+Q")
  42.         editMenu.add_command(label="Copy", command=self.copy, accelerator="Ctrl+C")
  43.         editMenu.add_command(label="Cut", command=self.cut, accelerator="Ctrl+X")
  44.         editMenu.add_command(label="Paste", command=self.paste, accelerator="Ctrl+V")
  45.         editMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
  46.         editMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
  47.         editMenu.add_command(label="Color", command=self.color)
  48.         editMenu.add_command(label="Bold", command=self.bold, accelerator="Ctrl+B")
  49.         editMenu.add_command(label="Italic", command=self.italic, accelerator="Ctrl+I")
  50.         editMenu.add_command(label="Underline", command=self.underline, accelerator="Ctrl+U")
  51.         editMenu.add_command(label="Overstrike", command=self.overstrike, accelerator="Ctrl+T")
  52.         editMenu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z")
  53.         editMenu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y")
  54.         self.config(menu=menubar)
  55.  
  56.         """Accelerator bindings. The cut, copy, and paste functions are not
  57.        bound to keyboard shortcuts because Windows already binds them, so if
  58.        Tkinter bound them as well whenever you typed ctrl+v the text would be
  59.        pasted twice."""
  60.         self.bind_all("<Control-n>", self.new)
  61.         self.bind_all("<Control-o>", self.open)
  62.         self.bind_all("<Control-s>", self.save)
  63.         self.bind_all("<Control-q>", self.exit)
  64.         self.bind_all("<Control-b>", self.bold)
  65.         self.bind_all("<Control-i>", self.italic)
  66.         self.bind_all("<Control-u>", self.underline)
  67.         self.bind_all("<Control-T>", self.overstrike)
  68.         self.bind_all("<Control-z>", self.undo)
  69.         self.bind_all("<Control-y>", self.redo)
  70.  
  71.         self.text = ScrolledText(self, state='normal', height=30, wrap='word', font = font, pady=2, padx=3, undo=True)
  72.         self.text.grid(column=0, row=0, sticky='NSEW')
  73.  
  74.         # Frame configuration
  75.         self.grid_columnconfigure(0, weight=1)
  76.         self.resizable(True, True)
  77.  
  78.     """Command functions. *args is included because the keyboard bindings pass
  79.    two arguments to the functions, while clicking in the menu passes only 1."""
  80.  
  81.     def new(self, *args):
  82.         """Creates a new window."""
  83.         app = Application()
  84.         app.title('Python Text Editor')
  85.         app.option_add('*tearOff', False)
  86.         app.mainloop()
  87.  
  88.     def color(self):
  89.         """Changes selected text color."""
  90.         try:
  91.             (rgb, hx) = tkinter.colorchooser.askcolor()
  92.             self.text.tag_add('color', 'sel.first', 'sel.last')
  93.             self.text.tag_configure('color', foreground=hx)
  94.         except TclError:
  95.             pass
  96.  
  97.     def bold(self, *args):
  98.         """Toggles bold for selected text."""
  99.         try:
  100.             current_tags = self.text.tag_names("sel.first")
  101.             if "bold" in current_tags:
  102.                 self.text.tag_remove("bold", "sel.first", "sel.last")
  103.             else:
  104.                 self.text.tag_add("bold", "sel.first", "sel.last")
  105.                 bold_font = Font(self.text, self.text.cget("font"))
  106.                 bold_font.configure(weight="bold")
  107.                 self.text.tag_configure("bold", font=bold_font)
  108.         except TclError:
  109.             pass
  110.  
  111.     def italic(self, *args):
  112.         """Toggles italic for selected text."""
  113.         try:
  114.             current_tags = self.text.tag_names("sel.first")
  115.             if "italic" in current_tags:
  116.                 self.text.tag_remove("italic", "sel.first", "sel.last")
  117.             else:
  118.                 self.text.tag_add("italic", "sel.first", "sel.last")
  119.                 italic_font = Font(self.text, self.text.cget("font"))
  120.                 italic_font.configure(slant="italic")
  121.                 self.text.tag_configure("italic", font=italic_font)
  122.         except TclError:
  123.             pass
  124.  
  125.     def underline(self, *args):
  126.         """Toggles underline for selected text."""
  127.         try:
  128.             current_tags = self.text.tag_names("sel.first")
  129.             if "underline" in current_tags:
  130.                 self.text.tag_remove("underline", "sel.first", "sel.last")
  131.             else:
  132.                 self.text.tag_add("underline", "sel.first", "sel.last")
  133.                 underline_font = Font(self.text, self.text.cget("font"))
  134.                 underline_font.configure(underline=1)
  135.                 self.text.tag_configure("underline", font=underline_font)
  136.         except TclError:
  137.             pass
  138.  
  139.     def overstrike(self, *args):
  140.         """Toggles overstrike for selected text."""
  141.         try:
  142.             current_tags = self.text.tag_names("sel.first")
  143.             if "overstrike" in current_tags:
  144.                 self.text.tag_remove("overstrike", "sel.first", "sel.last")
  145.             else:
  146.                 self.text.tag_add("overstrike", "sel.first", "sel.last")
  147.                 overstrike_font = Font(self.text, self.text.cget("font"))
  148.                 overstrike_font.configure(overstrike=1)
  149.                 self.text.tag_configure("overstrike", font=overstrike_font)
  150.         except TclError:
  151.             pass
  152.  
  153.     def undo(self, *args):
  154.         """Undo function"""
  155.         try:
  156.             self.text.edit_undo()
  157.         except TclError:
  158.             pass
  159.  
  160.     def redo(self, *args):
  161.         """Redo function"""
  162.         try:
  163.             self.text.edit_redo()
  164.         except TclError:
  165.             pass
  166.  
  167.     def copy(self, *args):
  168.         """Copy text"""
  169.         self.clipboard_clear()
  170.         self.clipboard_append(self.text.selection_get())
  171.  
  172.     def cut(self, *args):
  173.         """Cut text"""
  174.         self.copy
  175.         self.text.delete("sel.first", "sel.last")
  176.  
  177.     def paste(self, *args):
  178.         """Paste text"""
  179.         insertion = self.selection_get(selection = "CLIPBOARD")
  180.         self.text.insert(0.0, insertion)
  181.  
  182.     def open(self, *args):
  183.         """Opens a file dialog to open a plain text file."""
  184.         filename = tkinter.filedialog.askopenfilename()
  185.  
  186.         with open(filename) as f:
  187.             text = f.read()
  188.  
  189.         self.text.delete("1.0", "end")
  190.         self.text.insert('insert', text)
  191.  
  192.     def save(self, *args):
  193.         try:
  194.             """Opens a file dialog to save the text in plain text format."""
  195.             text = self.text.get("1.0", "end")
  196.             filename = tkinter.filedialog.asksaveasfilename()
  197.  
  198.             with open(filename, 'w') as f:
  199.                 f.write(text)
  200.         except FileNotFoundError:
  201.             pass
  202.  
  203.     def exit(self, *args):
  204.         """Exits the program."""
  205.         self.quit()
  206.  
  207. if __name__ == "__main__":
  208.     app=Application()
  209.     app.title('Python Text Editor')
  210.     app.option_add('*tearOff', False)
  211.     app.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement