Advertisement
Techpad

TechNotes 4

Mar 16th, 2021
1,854
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
E 1.96 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import messagebox as mb
  3. import os
  4. _root = frame1
  5.  
  6. filepath0 = ''
  7. def getnewpath():
  8.     global filepath0
  9.     global os
  10.     filepath1 = 'T:/Storage/Documents/Untitled'
  11.     rep = 0
  12.     while True:
  13.         if os.path.exists(filepath1 + str(rep) + '.txt'):
  14.             rep += 1
  15.         else:
  16.             filepath0 = filepath1 + str(rep) + '.txt'
  17.             break
  18.  
  19. getnewpath()
  20.  
  21. textarea = tk.Text(_root, font='consolas', bd=0)
  22.  
  23. menubar = tk.Frame(_root, bd=1, relief='solid', bg='white')
  24.  
  25. tascrollbar = tk.Scrollbar(textarea, cursor='arrow')
  26.  
  27. textarea.config(yscrollcommand=tascrollbar.set)
  28. tascrollbar.config(command=textarea.yview)
  29.  
  30. def open_file(path):
  31.     global textarea
  32.     global filepath0
  33.     filepath0 = path
  34.     _file = open(path, 'r')
  35.     try:
  36.         _conts = _file.read()
  37.         _file.close()
  38.         textarea.delete(1.0, 'end')
  39.         textarea.insert(1.0, _conts)
  40.     except UnicodeDecodeError:
  41.         textarea.delete(1.0, 'end')
  42.         textarea.insert(1.0, 'Unable to open file\nFile is not in text format.')
  43.  
  44. def save_file():
  45.     global filepath0
  46.     global textarea
  47.     try:
  48.         sav = open(filepath0, 'w')
  49.         sav.write(textarea.get(1.0, 'end')[:-1])
  50.         sav.close()
  51.     except PermissionError:
  52.         global mb
  53.         mb.showinfo("Permission Denied", "You do not seem to have permission to edit this file.")
  54.  
  55. def new_file():
  56.     global getnewpath
  57.     global textarea
  58.     textarea.delete(1.0, 'end')
  59.     getnewpath()
  60.  
  61. newfilebutton = tk.Button(menubar, bd=0, bg='white', activebackground='lightgray', text='New', command=new_file)
  62. savefilebutton = tk.Button(menubar, bd=0, bg='white', activebackground='lightgray', text='Save', command=save_file)
  63.  
  64. menubar.pack(side='top', anchor='n', fill='x')
  65. newfilebutton.pack(anchor='w', side='left')
  66. savefilebutton.pack(anchor='w', side='left')
  67. textarea.pack(expand=True, fill='both')
  68. tascrollbar.pack(side='right', anchor='e', fill='y')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement