Having a text editor made with Python and with the graphic interface of Tkinter, I can load the contents of an extension document ".txt". But, also, without doing anything special, I get to load other types of documents such as XML files, PDF (although you do not understand much what loads but loads something ... :)).
This is the code:
# encoding: utf-8
import Tkinter as tk
import tkFont
import tkMessageBox as MessageBox
import tkFileDialog as FileDialog
from ScrolledText import ScrolledText
######## Python 3 ###########
#import tkinter as tk
#import tkinter.font as tkFont
#from tkinter import messagebox as MessageBox
#from tkinter import filedialog as FileDialog
#-> parece ya integrada en el import de * (tkinter.scrolledtext)
import os
class MiTkinter(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Ruta a guardar por si, más adelante, se guarda el archivo...
self.ruta = ''
self.prim_color = 'black'
self.sec_color = 'white'
self.ter_color = 'grey'
menubar = tk.Menu(self, bg=self.prim_color, fg=self.sec_color)
self.config(menu=menubar)
filemenu = tk.Menu(menubar, tearoff=0, bg=self.prim_color, fg=self.sec_color)
menubar.add_cascade(label='Archivo', menu=filemenu)
filemenu.add_command(label='Abrir', command=self.archivo_abrir)
filemenu.add_command(label='Cerrar', command=self.archivo_cerrar)
filemenu.add_separator()
filemenu.add_command(label='Salir', command=self.archivo_salir)
self.parent_frame = tk.Frame(self, bg=self.ter_color, padx=10, pady=10, width=300, height=345, relief="sunken")
self.parent_frame.pack(fill="both", expand=True)
self._text1_font = tkFont.Font(family='Consolas', size=10)
frame_text1 = tk.Frame(self.parent_frame, width=300, height=345, relief="sunken")
frame_text1.pack_propagate(False)
frame_text1.grid(row=0, column=0, padx=10, pady=10)
self.text1 = tk.Text(frame_text1,
wrap='word',
bd=0,
padx=6,
pady=4,
font=self._text1_font,
selectbackground='lightblue',
width=24,
height=16,
bg=self.prim_color,
fg=self.sec_color,
insertbackground=self.sec_color,
highlightbackground=self.prim_color,
highlightcolor=self.sec_color,
yscrollcommand=self.on_textscroll
)
self.text1.pack(fill="both", expand=True)
self.yscrollbar_gnral = tk.Scrollbar(self.parent_frame)
self.yscrollbar_gnral.grid(row=0, column=1, sticky=tk.NS, padx=2, pady=2)
self.yscrollbar_gnral.config(command=self.on_scrollbar, bg=self.prim_color, bd=1)
def archivo_abrir(self):
'''Abrir archivo a analizar.'''
print('Abrir archivo')
#>> Ventana de Archivo :: Abrir
self.ruta = FileDialog.askopenfilename(
title='Abrir un Archivo',
# Ruta por defecto para abrir archivo(s)
# -> la raíz del aplicativo
initialdir='.',
# -> la raíz del equipo
####initialdir='/',
# -> por defecto, si no se incluye el parámetro,
# >> última ruta abierta
filetypes=(
('Archivos de texto', '*.txt'),
('Todos los archivos', '*.*')
)
)
# Verificando que es una ruta válida para:
# -> abrir el archivo en modo de lectura ('r')
# >> ** NOTA **:
# se ha observado que, al abrirse el archivo, se agrega
# un nuevo salto de línea (\n) al final del contenido.
# Tener en cuenta esto al efectuar la acción de guardar.
# [Cancelar] pulsado => Tupla vacía => ()
if (self.ruta is () or self.ruta == ''):
self.ruta = ''
print('Abrir archivo >> acción CANCELADA')
elif (self.ruta):
fichero = open(self.ruta, 'r')
fichero_contenido = fichero.read()
# Asegurando que el TEXT queda vacío antes de cargar fichero_contenido
self.text1.delete(1.0, 'end')
# Pasando fichero_contenido al TEXT adecuado
self.text1.insert(1.0, fichero_contenido)
# Para colocar el cursor al principio del fichero_contenido tras cargarlo
# -> si no pone esta línea, el cursor aparecerá al final de fichero_contenido
self.text1.mark_set('insert', '%d.%d' % (0.0, 1.0))
fichero.close()
print('Abrir archivo >> abierto correctamente ¡OK!')
def archivo_cerrar(self):
'''Cerrar documento abierto.'''
print('Cerrado documento')
self.text1.delete(1.0, 'end')
def archivo_salir(self):
'''Saliendo del programa tras confirmación de la acción demandada.'''
print('Saliendo del Programa :(')
# >> Ventana de Confirmación de [Si|No]
# -> según lo que pulse (Si|No >> True|False),
# se podrá hacer una cosa u otra
''''''
msgb_conf = '¿Desea salir del programa?'
confirm_siNo = MessageBox.askyesno('Confirmación ~ ¿?', msgb_conf)
if (confirm_siNo):
# self.quit()
# o
self.destroy()
def on_scrollbar(self, *args):
'''Scrolls both text widgets when the scrollbar is moved.'''
self.text1.yview(*args)
def on_textscroll(self, *args):
'''Moves the scrollbar and scrolls text widgets when the mousewheel
is moved on a text widget.'''
self.yscrollbar_gnral.set(*args)
self.on_scrollbar('moveto', args[0])
if __name__ == '__main__':
# Limpia consola antes de empezar ejecución
os.system('clear')
root = MiTkinter()
root.title('Probando ~ Carga de .DOCs')
root.geometry('{}x{}+{}+{}'.format(360, 390, 400, 100))
root.mainloop()
The issue is that, apart from loading, correctly, the text file content with extension ".txt", it would be nice if the content of ".doc" or ".docx" files could be uploaded, that is to say , Microsoft Word files.
Right now, as the code is, when I open an Ms Word file, the indicative that it has been loaded correctly ( Abrir archivo >> abierto correctamente ¡OK!
) is printed by the terminal.
But the only thing that is seen inside the Text where, supposedly, this has been loaded that is seen in the image:
So, that's the question: can Word files be loaded in this type of editors like the code that happened?
If possible, or if someone knows or has done it before, can you tell me what it would be like?
EXTRA NOTE : first, I'm interested in how to load Ms Word documents in this type of editor.
But if, then, you can extend the question and know how to load the content of any type of file in this type of editor, well better than better ...:)