jardin.py 24.5 KB
Newer Older
mi@mondo's avatar
[email protected] committed
1 2 3
#!/usr/bin/env python3
# -*- coding: utf8 -*-

mi@mondo's avatar
[email protected] committed
4
# Copyright © 2020 Benoît Boudaud <https://miamondo.org>
mi@mondo's avatar
[email protected] committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import os 
import sys
import shutil
import tkinter as tk
import tkinter.messagebox
import tkinter.filedialog 
import webbrowser as wb
import subprocess
from PIL import Image, ImageTk

#==IMAGES=====================================================================

'''https://commons.wikimedia.org/wiki/File:Lycopersicum_philippinarum_''' +\
'''Blanco1.43b-original.png'''

'''https://commons.wikimedia.org/wiki/File:Wm._Elliott_and_Sons_''' +\
'''seedsmen_-_1898_(1898)_(14781700222).jpg'''

'''https://commons.wikimedia.org/wiki/File:Thomas_Horton_Ltd_-Thos.''' +\
'''_Horton_Pahiatua._Pear,_Williams'_Bon_Chretien;_Beurre_Diel_dessert_''' +\
'''pear_of_the_highest_quality._McKee_and_Co.,_Wellington_(ca_1904).''' +\
'''_(21270487152).jpg'''

'''https://commons.wikimedia.org/wiki/File:Althaea_or_Marshmallow,_''' +\
'''illustration_from_Fuchs_Wellcome_L0035310.jpg'''

'''https://commons.wikimedia.org/wiki/File:Herbier_de_l'Amateur_de_''' +\
'''Fleurs_BHL15897604.jpg'''

#==ICONES=====================================================================

# /usr/share/icons/oxygen/base/32x32/actions/list-add.png
# /usr/share/icons/oxygen/base/32x32/actions/list-remove.png
# /usr/share/icons/oxygen/base/32x32/actions/arrow-left.png
# /usr/share/icons/gnome/48x48/mimetypes/image-x-generic.png


# prerequis : xrandr

#==CLASSE=====================================================================

class Home(object):
    "Instanciation de la page d'accueil"

#--MÉTHODE--------------------------------------------------------------------

    def __init__(self, init):
        "Constructeur"

        if isinstance(init, dict):
            for i in init:
                setattr(self, i, init[i])

#--MÉTHODE--------------------------------------------------------------------

    def home(self):
        "Page d'accueil"

        # Récupération de la hauteur et de la largeur de l'écran principal:
        xrandr = subprocess.Popen('xrandr', text=True, stdout=subprocess.PIPE)
        for line in xrandr.stdout:
            if "primary" in line:
                for item in line.split():
                    if 'x' in item and '+' in item:
                        w = item.replace('x',' ').replace('+', ' ').split()[0]
                        h = item.replace('x',' ').replace('+', ' ').split()[1]
                        x = item.replace('x',' ').replace('+', ' ').split()[2]
                        y = item.replace('x',' ').replace('+', ' ').split()[3]

mi@mondo's avatar
[email protected] committed
87
        root = tk.Tk() ; root.title('Mon jardin numérique')
mi@mondo's avatar
[email protected] committed
88
        root.geometry("{}x{}+{}+{}".format(w, h, x, y))
mi@mondo's avatar
[email protected] committed
89
        root.config(bg='white')
mi@mondo's avatar
[email protected] committed
90 91 92 93 94 95 96 97 98 99

        # Traitement de l'image illustrant la page d'accueil
        images = [
            'Lycopersicum_philippinarum.png', 
            'elliott_and_sons_seedsmen.png',
            'thomas_horton_ltd.png',
            'althaea_officinalis.png',
            'Herbier_de_l_Amateur_de_Fleurs.png', 
            'list-add.png',
            'list-remove.png',
mi@mondo's avatar
[email protected] committed
100 101 102 103
            'arrow-left.png',
            'quit.png',
            'save.png',
            'blocnotes.png'
mi@mondo's avatar
[email protected] committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117
            ]

        for i, ima in enumerate(images): 
            im = Image.open(os.path.join(self.WD, 'images', ima))
            if i == 0:
                im.thumbnail((768,576))
            elif i > 0 and i < 5:
                im.thumbnail((256,192))
            else:
                im.thumbnail((24,24))                
            im2 = ImageTk.PhotoImage(im, master=root)
            images[i:i+1] = [im2]
        
        # Création des widgets                        
mi@mondo's avatar
[email protected] committed
118 119
        homepage = tk.LabelFrame(root, labelanchor='n', bg='white',
            text='Mon jardin numérique', font='Courier 70 bold italic', bd=0, 
mi@mondo's avatar
[email protected] committed
120 121 122 123 124 125 126 127
            fg='green', relief='groove', padx=50, pady=30)
        homepage.grid(padx=int(w)/3.75, pady=int(h)/6,
            sticky='nsew')

        welcome = tk.Button(homepage, image=images[0], bd=1, 
            bg='orange', cursor='hand2', relief='flat')
        welcome.grid(padx=200)
        
mi@mondo's avatar
[email protected] committed
128
        miamondo = tk.Button(homepage, bg='white', fg='black', 
mi@mondo's avatar
[email protected] committed
129
            font='Courier 20 bold', text='miamondo.org', bd=0,
mi@mondo's avatar
[email protected] committed
130
            highlightthickness=0, activebackground='white',
mi@mondo's avatar
[email protected] committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            activeforeground='orange', cursor='hand2',
            command=lambda:wb.open_new_tab('http://miamondo.org'))
        miamondo.grid(row=1, pady=20)

        init = dict()
        init = {
            'WD':self.WD,
            'w':w,
            'h':h,
            'x':x,
            'y':y,
            'root':root,
            'homepage':homepage,
            'welcome':welcome,
            'miamondo':miamondo,
            'images':images
            }
        self.categories = Categories(init)
        welcome['command'] = self.categories.categories

        root.mainloop() # Démarrage du gestionnaire d'événements

#==CLASSE=====================================================================

class Categories(object):
    "Instanciation de la page d'accueil"

#--MÉTHODE--------------------------------------------------------------------

    def __init__(self, init):
        "Constructeur"

        if isinstance(init, dict):
            for i in init:
                setattr(self, i, init[i])

#--MÉTHODE--------------------------------------------------------------------

    def categories(self):
        "Bouton de menu qui permet d'ouvrir \"légumes\" ou \"fruits\""

        for child in self.root.winfo_children():
            if child.winfo_class() == 'Panedwindow':
                child.grid_remove()
            else:
                child.grid()

        # Disparition provisoire des widgets de la page d'accueil:
        self.welcome.grid_remove() ; self.miamondo.grid_remove()

mi@mondo's avatar
[email protected] committed
181
        # Quatre catégories vont être instanciées:
mi@mondo's avatar
[email protected] committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        select = [
            ['legumes', 'Légumes', 'Légume'], 
            ['fruits', 'Fruits', 'Fruit'], 
            ['herbes', 'Herbes', 'Herbe'],
            ['fleurs', 'Fleurs', 'Fleur']
            ]

        # Création des boutons de menu (Menubutton):
        for i, item in enumerate(select):
            self.menu_button = tk.Menubutton(self.homepage, bg='white', bd=3,
                relief='flat', font='Courier 20 bold',  cursor='hand2', 
                fg='orange', text=item[1], image=self.images[i+1], 
                compound='top', highlightbackground='orange', 
                highlightthickness=2)
            self.menu_button.grid(row=1,column=i, padx=25)
mi@mondo's avatar
[email protected] committed
197
            self.menu_button.menu=tk.Menu(self.menu_button, bg='white', bd=1, 
mi@mondo's avatar
[email protected] committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
                relief='flat', font='Courier 14', tearoff='0') 
            self.menu_button['menu'] = self.menu_button.menu

            # Premier et deuxième bouton du menu: 
            for j, action in enumerate([ ['rajouter', 'green'],
                ['supprimer', 'red']]): 
                init = dict()
                init = {
                    'WD':self.WD,
                    'w':self.w,
                    'h':self.h,
                    'x':self.x,
                    'y':self.y,
                    'root':self.root,
                    'homepage':self.homepage,
                    'welcome':self.welcome,
                    'miamondo':self.miamondo,
                    'images':self.images,
                    'item':item,
                    'action':action[0]
                    }
                self.addOrRemove = AddOrRemove(init)                    
                self.menu_button.menu.add_command(label=' {0} une espèce'.\
                    format(action[0].capitalize()), image=self.images[j+5], 
mi@mondo's avatar
[email protected] committed
222
                    compound='left',background='white',font='Courier 14 bold',
mi@mondo's avatar
[email protected] committed
223 224 225 226 227
                    activeforeground=action[1], command=self.addOrRemove.\
                    addOrRemove)
                self.menu_button.menu.add_separator()

            # Création des pages enregistrées:
mi@mondo's avatar
[email protected] committed
228 229 230 231 232 233 234 235 236 237
            subprocess.Popen(['mkdir', '{}'.format(os.path.join(self.WD,
                'categories', item[0].capitalize()))], text=True,
                stderr=subprocess.PIPE)
            subprocess.Popen(['touch', '{}'.format(os.path.join(self.WD,
                'categories', item[0].capitalize(), item[0]))], text=True,
                stderr=subprocess.PIPE)
            subprocess.Popen(['touch', '{}'.format(os.path.join(self.WD,
                'categories', item[0].capitalize(), '{}_texteditor1'.format(
                item[0])))], text=True, stderr=subprocess.PIPE)
            self.root.after(200)
mi@mondo's avatar
[email protected] committed
238 239 240
            setattr(self, item[0], list())
            setattr(self, '{}_2'.format(item[0]), list())
            setattr(self, 'dict_{}_images'.format(item[0]), dict()) 
mi@mondo's avatar
[email protected] committed
241 242
            with open(os.path.join(self.WD, 'categories', item[0].capitalize(
                ), item[0]), 'r') as ofile: 
mi@mondo's avatar
[email protected] committed
243 244 245 246 247 248 249 250 251 252
                for line in ofile.readlines():
                    getattr(self, item[0]).append(line.split(':')[0])
                    getattr(self, 'dict_{}_images'.format(item[0])
                        )[line.split(':')[0]]=line.split(':')[1].replace(
                        '\n', '')

            for name in getattr(self, item[0]):
                if name not in getattr(self, '{}_2'.format(item[0])):
                    getattr(self, '{}_2'.format(item[0])).append(name)
            getattr(self, '{}_2'.format(item[0])).sort()
mi@mondo's avatar
[email protected] committed
253 254
            with open(os.path.join(self.WD,'categories',item[0].capitalize(),
                item[0]),'w')as wfile:
mi@mondo's avatar
[email protected] committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                for name in getattr(self, '{}_2'.format(item[0])):
                    wfile.write('{0}:{1}\n'.format(name, getattr(self,\
                    'dict_{}_images'.format(item[0]))[name]))

            setattr(self, '{}_names_images'.format(item[0]), list())
            for i, name in enumerate(getattr(self, '{}_2'.format(item[0]))):
                new_im = Image.open(getattr(self, 'dict_{}_images'.\
                    format(item[0]))[name])
                new_im.thumbnail((24,24))                
                new_im_2 = ImageTk.PhotoImage(new_im, 
                    master=self.root)
                getattr(self, '{}_names_images'.format(item[0])).append(
                    [name, new_im_2])


            for name_im in getattr(self, '{}_names_images'.format(item[0])):
                init = dict()
                init = {
                    'WD':self.WD,
                    'w':self.w,
                    'h':self.h,
                    'x':self.x,
                    'y':self.y,
                    'root':self.root,
                    'homepage':self.homepage,
                    'welcome':self.welcome,
                    'miamondo':self.miamondo,
                    'images':self.images,
                    'item':item,
                    'action':action[0],
                    'name':name_im[0],
                    'image':getattr(self, 'dict_{}_images'.format(
                        item[0]))[name_im[0]]
                    }
                
                self.openPage = OpenPage(init)
                self.menu_button.menu.add_command(label=' {}'.format(
                    name_im[0]), image=name_im[1], compound='left', 
mi@mondo's avatar
[email protected] committed
293
                    font='Courier 14 bold', background='white', 
mi@mondo's avatar
[email protected] committed
294 295 296 297
                    command=self.openPage.openPage)

        # Création du bouton de retour à la page d'accueil :

mi@mondo's avatar
[email protected] committed
298
        self.come_back_home = tk.Button(self.root, bg='white', text='Accueil',
mi@mondo's avatar
[email protected] committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
            font='Courier 20 bold', image=self.images[7], 
            compound='left', fg='maroon', bd=0, highlightthickness=0, 
            cursor='hand2', command=self.close_page)
        self.come_back_home.grid(row=2)

#--MÉTHODE--------------------------------------------------------------------

    def close_page(self):
        'fermeture de la page courante et retour à la page d\'accueil'

        for child in self.homepage.winfo_children():
            child.grid_remove()
        self.welcome.grid() ; self.miamondo.grid()

#==CLASSE=====================================================================

class AddOrRemove(object):
    "Instanciation de la page d'accueil"

#--MÉTHODE--------------------------------------------------------------------

    def __init__(self, init):
        "Constructeur"

        if isinstance(init, dict):
            for i in init:
                setattr(self, i, init[i])


#--MÉTHODE--------------------------------------------------------------------

    def addOrRemove(self):
        "Méthode qui ouvre une fenêtre de dialogue pour rajouter " + \
        "une nouvelle espèce dans le menu déroulant."
        
mi@mondo's avatar
[email protected] committed
334
        self.toplevel = tk.Toplevel(bg='white')
mi@mondo's avatar
[email protected] committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        self.toplevel.title("{0} à {1}".format(self.item[2], self.action))
        self.toplevel.lift()
        self.toplevel.transient(self.root)
        self.toplevel.resizable(False, False)
        self.entry = tk.Entry(self.toplevel, width=30, font="Courier 14")
        self.entry.grid(row=1, padx=10, pady=10)
        if self.action == 'rajouter':        
            self.entry.bind('<Return>', self.save_value)
        else:
            self.entry.bind('<Return>', lambda event, 
            item=self.item : self.remove_element(item))

#--MÉTHODE--------------------------------------------------------------------

    def save_value(self, event):
        "Enregistrement de la nouvelle valeur"

        self.saved_value = self.entry.get().capitalize()
        self.toplevel.withdraw()      
        add_image = tkinter.messagebox.askquestion('Importer une image',
            'Espèce enregistrée. Souhaitez-vous importer une image pour '+\
            'illustrer la nouvelle page intitulée {}?'.format(
            self.saved_value), icon="question")     
        if add_image == 'yes':
            select_image = tkinter.filedialog.askopenfilename(
                title="Importer une image", filetypes=[('png files','.png'),
                ('all files','.*')]) 
        else:
            select_image = os.path.join(self.WD, 'images',
                'image-x-generic.png')
        image_basename = os.path.basename(select_image)
        extension = os.path.splitext(image_basename)[1].lower()
        try:
            shutil.copy(select_image, os.path.join(self.WD,
                "images/downloaded_images"))
        except:
            "same file"
        os.rename(os.path.join(self.WD, 'images', 'downloaded_images',
            image_basename), os.path.join(self.WD, 'images',
            'downloaded_images', '{}{}'.format(self.saved_value.lower(), 
            extension))) 

        os.system("echo {0}:{1} >> ./{2}".format(self.saved_value, 
            os.path.join(self.WD, 'images', 'downloaded_images',
            '{}{}'.format(self.saved_value.lower(), extension)), 
mi@mondo's avatar
[email protected] committed
380
            os.path.join(self.WD, 'categories', self.item[0].capitalize(), self.item[0])))
mi@mondo's avatar
[email protected] committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
        if add_image == 'yes':
            tkinter.messagebox.showinfo("Image importée",
                "L'image a été importée")

        init = dict()
        init = {
            'WD':self.WD,
            'w':self.w,
            'h':self.h,
            'x':self.x,
            'y':self.y,
            'root':self.root,
            'homepage':self.homepage,
            'welcome':self.welcome,
            'miamondo':self.miamondo,
mi@mondo's avatar
[email protected] committed
396 397
            'images':self.images,
            'item':self.item
mi@mondo's avatar
[email protected] committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
            }
        self.categories = Categories(init)
        self.categories.categories()


#--MÉTHODE--------------------------------------------------------------------

    def remove_element(self, item):
        "Suppression d'une espèce"

        self.removed_value = self.entry.get().capitalize()
        self.toplevel.withdraw()      
        confirm = tkinter.messagebox.askquestion("Supprimer?",
            'Voulez-vous vraiment supprimer la page intitulée {}? Cette '.\
            format(self.removed_value) + 'opération est irréversible!', 
            icon="question")     
        if confirm == 'yes':
mi@mondo's avatar
[email protected] committed
415
            with open(os.path.join(self.WD, 'categories', self.item[0].capitalize(),
mi@mondo's avatar
[email protected] committed
416 417 418 419 420 421
                self.item[0]), 'r') as ofile:
                rfile = ofile.readlines()
                for line in rfile:
                    if self.removed_value in line:
                        rfile.remove(line)
            with open(os.path.join(self.WD, 'categories', 
mi@mondo's avatar
[email protected] committed
422
                self.item[0].capitalize(), self.item[0]), 'w') as wfile:
mi@mondo's avatar
[email protected] committed
423 424
                for line in rfile:                    
                    wfile.write(line)
mi@mondo's avatar
[email protected] committed
425 426 427 428 429 430 431 432
            with open (os.path.join(self.WD, 'categories', self.item[0].capitalize(), '{}_texteditor1'.format(self.item[0])), 'r') as rfile:
                lines = rfile.readlines()
                for line in lines:
                    if self.removed_value in line:
                        lines.remove(line)
            with open (os.path.join(self.WD, 'categories', self.item[0].capitalize(), '{}_texteditor1'.format(self.item[0])), 'w') as wfile:
                for line in lines:
                    wfile.write(line)
mi@mondo's avatar
[email protected] committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            for image in os.listdir(os.path.join(self.WD, 'images',
                'downloaded_images')):
                if image.startswith(self.removed_value.lower()):
                    os.remove(os.path.join(self.WD, 'images',
                        'downloaded_images', image))
            tkinter.messagebox.showinfo\
                ("Page supprimée", "La page a été supprimée")

        init = dict()
        init = {
            'WD':self.WD,
            'w':self.w,
            'h':self.h,
            'x':self.x,
            'y':self.y,
            'root':self.root,
            'homepage':self.homepage,
            'welcome':self.welcome,
            'miamondo':self.miamondo,
mi@mondo's avatar
[email protected] committed
452 453
            'images':self.images,
            'item':self.item
mi@mondo's avatar
[email protected] committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            }
        self.categories = Categories(init)
        self.categories.categories()

#==CLASSE=====================================================================

class OpenPage(object):
    "open the selected page"

#--MÉTHODE--------------------------------------------------------------------

    def __init__(self, init):
        "Constructeur"

        if isinstance(init, dict):
            for i in init:
                setattr(self, i, init[i])


#--MÉTHODE--------------------------------------------------------------------

    def openPage(self):
        "Ouvre la page de l'espèce sélectionnée"

        self.logo = Image.open(self.image) ; self.logo.thumbnail((192,192))                
        self.logo = ImageTk.PhotoImage(self.logo, master=self.root)

        for child in self.root.winfo_children():
            if child.winfo_class() != 'Toplevel':
                child.grid_remove()

        self.paned_window = tk.PanedWindow(self.root, bg = 'green',
            height=self.h, width=self.w, orient='vertical', sashpad=1, 
            sashrelief='ridge', sashwidth=1)
        self.paned_window.grid() 
        
mi@mondo's avatar
[email protected] committed
490
        self.frame_1 = tk.Frame(self.paned_window, bg='white')        
mi@mondo's avatar
[email protected] committed
491 492 493 494 495
        self.paned_window.add(self.frame_1)

        self.buttons = tk.Label(self.frame_1, bg='green', bd=1, width=2, height=2)
        self.buttons.grid(row=0, column=0, columnspan=2, sticky='w')

mi@mondo's avatar
[email protected] committed
496
        self.button_1 = tk.Button(self.frame_1, bg='white', image=self.logo, 
mi@mondo's avatar
[email protected] committed
497
            font='Courier 30 bold', fg='black', bd=0, highlightthickness=0, 
mi@mondo's avatar
[email protected] committed
498
            activebackground='white', activeforeground='green', 
mi@mondo's avatar
[email protected] committed
499 500 501
            relief='ridge', cursor='hand2')       
        self.button_1.grid(row=1, column=0, sticky='w', padx=10, pady=5) 

mi@mondo's avatar
[email protected] committed
502
        self.label_1 = tk.Button(self.frame_1, bg='white', fg='black', bd=0,
mi@mondo's avatar
[email protected] committed
503 504
            text=self.name.capitalize(), font='Courier 40 bold',  
            highlightthickness=0, activeforeground='green', cursor='hand2',
mi@mondo's avatar
[email protected] committed
505
            activebackground='white', command=lambda:wb.open_new_tab(
mi@mondo's avatar
[email protected] committed
506 507 508 509 510 511 512
            'https://fr.wikipedia.org/wiki/{}'.format(self.name)))        
        self.label_1.grid(row=1, column=1, sticky='w', pady=20)    

        self.sub_paned_window = tk.PanedWindow(self.paned_window, bg='green', 
            orient='horizontal', sashpad=1, sashrelief='ridge', sashwidth=1)
        self.paned_window.add(self.sub_paned_window)

mi@mondo's avatar
[email protected] committed
513 514 515 516 517
        self.textEditor = tk.Text(self.sub_paned_window, height=20, width=100, 
            bg='white', spacing1=70, spacing2=10, font='Courier 14 bold')        
        self.sub_paned_window.add(self.textEditor)

        self.subframe = tk.Frame(self.sub_paned_window, bg='white')        
mi@mondo's avatar
[email protected] committed
518 519
        self.sub_paned_window.add(self.subframe)

mi@mondo's avatar
[email protected] committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        self.textEditorTitle = tk.Label(self.textEditor, font='Courier 20 bold', text='  Bloc-Notes', image=self.images[10], compound='left', pady=10, bg='orange', fg='white')
        self.textEditorTitle.pack(fill='both')

        with open (os.path.join(self.WD, 'categories', self.item[0].capitalize(), '{}_texteditor1'.format(self.item[0])), 'r') as rfile:
            for line in rfile.readlines():
                if line.startswith(self.name):
                    self.textEditor.insert(1.0, line.split(':')[1].replace('\\n','\n'))
                
        self.sub_paned_window2 = tk.PanedWindow(self.paned_window, bg='green', 
            orient='horizontal', sashpad=1, sashrelief='ridge', sashwidth=1)
        self.paned_window.add(self.sub_paned_window2)

        self.texteditor_2 = tk.Text(self.sub_paned_window2, bg='white', 
            height=20, width=50)        
        self.sub_paned_window2.add(self.texteditor_2)

        self.subframe2 = tk.Frame(self.sub_paned_window2, bg='white')        
        self.sub_paned_window2.add(self.subframe2)

mi@mondo's avatar
[email protected] committed
539 540 541 542 543 544 545 546 547 548 549
        init = dict()
        init = {
            'WD':self.WD,
            'w':self.w,
            'h':self.h,
            'x':self.x,
            'y':self.y,
            'root':self.root,
            'homepage':self.homepage,
            'welcome':self.welcome,
            'miamondo':self.miamondo,
mi@mondo's avatar
[email protected] committed
550 551
            'images':self.images,
            'item':self.item
mi@mondo's avatar
[email protected] committed
552 553 554
            }
        self.categories = Categories(init)
   
mi@mondo's avatar
[email protected] committed
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        self.comeBackPreviousPage = tk.Button(self.buttons, bg='white',
            text='Retour', font='Courier 16 bold', image=self.images[7], 
            compound='left', cursor='hand2', relief='ridge',
            command=self.categories.categories)
        self.comeBackPreviousPage.pack(side='left')
        self.destroyApp = tk.Button(self.buttons, bg='white',
            text='Quitter', font='Courier 16 bold', image=self.images[8], 
            compound='left', cursor='hand2', relief='ridge',
            command=self.root.destroy)
        self.destroyApp.pack(side='left')
        self.save = tk.Button(self.buttons, bg='white',
            text='Enregistrer', font='Courier 16 bold', image=self.images[9], 
            compound='left', cursor='hand2', relief='ridge',
            command=self.saveTextEditor1)
        self.save.pack(side='left')

    def saveTextEditor1(self):

        with open (os.path.join(self.WD, 'categories', self.item[0].capitalize(), '{}_texteditor1'.format(self.item[0])), 'r') as rfile:
            lines2 = rfile.readlines()
            lines = []
            for line2 in lines2:
                if line2 not in lines:
                    lines.append(line2)
            lineStarts = list()
            for line in lines:
                if line.split(':')[0] not in lineStarts:
                    lineStarts.append(line.split(':')[0])
                print(lineStarts)
            if self.name not in lineStarts:
                lines.append('{}:{}\n'.format(self.name, self.textEditor.get(1.0, 'end').replace('\n','\\n')))
            else:
                for i, line in enumerate(lines):
                    if line.startswith(self.name):
                        lines[i:i+1] = ['{}:{}\n'.format(line.split(':')[0], self.textEditor.get(1.0, 'end').replace('\n','\\n'))]
            with open (os.path.join(self.WD, 'categories', self.item[0].capitalize(), '{}_texteditor1'.format(self.item[0])), 'w') as wfile:
                for line in lines:                
                    wfile.write(line)

        self.confirm = tkinter.messagebox.showinfo\
                ('Données mises à jour', 'Données mises à jour')        
mi@mondo's avatar
[email protected] committed
596 597 598 599 600 601 602 603 604

# ============MAIN PROGRAMM ==================================================

if __name__ == "__main__": 

    init = {
        'WD': os.path.dirname(sys.argv[0]), # Répertoire courant
        }
    home = Home(init) 
mi@mondo's avatar
[email protected] committed
605
    home.home()