from AppliDef import *
from Graph import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import csv
from scipy.stats import linregress
import numpy as np
import winsound
from numpy import log, exp, sqrt, cos, sin, tan, pi, abs, arcsin, arccos, arctan


def ExtractNameFile(PathFile):
    File = ''
    for i in range(len(PathFile), 0, -1):
        if PathFile[i - 1:i] != '/':
            File = File + PathFile[i - 1:i]
        else:
            break
    File2 = ''
    for i in range(len(File), 0, -1):
        File2 = File2 + File[i - 1:i]
    File2 = File2[0:len(File2) - 4]
    return File2


class FrmTableur(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.InfoAction = False
        self.FileSaved = False
        self.ModifTab = False
        self.ParaTab = False
        self.GraphAffich = False
        self.TooltipAction = None
        self.FileCSV = ''
        self.Graph = None
        self.ParaGraph = None
        self.DatasFile = []

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmTableur/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmTableur/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.174)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.080)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmTableur/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond,
            int(self.SX * 0.975), int(self.SY * 0.018), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmTableur)

        self.NoNewfile = 1
        self.NameFile = "Tableur_" + str(self.NoNewfile)
        self.LabelNameFile = self.CanvasFrmFond.create_text(int(self.SX * 0.01), int(self.SY * 0.016),
                                                            text=self.NameFile, font=FontLabel2(10), anchor=tk.W)
        self.CanvasFrmFond.addtag_withtag('LabelNameFile', self.LabelNameFile)

        self.ImgBtnNewFile, wsize, hsize, self.CanvasBtnNewFile, self.ImgCanvasBtnNewFile = CanInWindow(
            'Media/FrmTableur/BtnNew/', self.RatioX, self.RatioY, self.CanvasFrmFond, int(self.SX * 0.025),
            int(self.SY * 0.057), 0)
        ChangeCursor(self.CanvasBtnNewFile)
        self.CanvasBtnNewFile.bind('<ButtonPress-1>',
                                   lambda action: self.CanvasBtnNewFile.itemconfig(self.ImgCanvasBtnNewFile,
                                                                                   image=self.ImgBtnNewFile[1]))
        self.CanvasBtnNewFile.bind('<ButtonRelease-1>', self.AffichNewFile)
        self.CanvasBtnNewFile.bind('<Motion>', self.MoveNewFile)

        self.ImgBtnOpen, wsize, hsize, self.CanvasBtnOpen, self.ImgCanvasBtnOpen = CanInWindow(
            'Media/FrmTableur/BtnOpen/', self.RatioX, self.RatioY, self.CanvasFrmFond, int(self.SX * 0.080),
            int(self.SY * 0.059), 0)
        ChangeCursor(self.CanvasBtnOpen)
        self.CanvasBtnOpen.bind('<ButtonPress-1>',
                                lambda action: self.CanvasBtnOpen.itemconfig(self.ImgCanvasBtnOpen,
                                                                             image=self.ImgBtnOpen[1]))
        self.CanvasBtnOpen.bind('<ButtonRelease-1>', self.OpenFile)
        self.CanvasBtnOpen.bind('<Motion>', self.MoveOpenFile)

        self.ImgBtnSave, wsize, hsize, self.CanvasBtnSave, self.ImgCanvasBtnSave = CanInWindow(
            'Media/FrmTableur/BtnSave/', self.RatioX, self.RatioY, self.CanvasFrmFond, int(self.SX * 0.135),
            int(self.SY * 0.057), 0)
        ChangeCursor(self.CanvasBtnSave)
        self.CanvasBtnSave.bind('<ButtonPress-1>',
                                lambda action: self.CanvasBtnSave.itemconfig(self.ImgCanvasBtnSave,
                                                                             image=self.ImgBtnSave[1]))
        self.CanvasBtnSave.bind('<ButtonRelease-1>', self.ActionSaveFile)
        self.CanvasBtnSave.bind('<Motion>', self.MoveSaveFile)

        self.BtnSaveSous = BtnAction(self.CanvasFrmFond, int(self.SX * 0.185), int(self.SY * 0.057), self.RatioX,
                                     self.RatioY, 'Media/FrmTableur/BtnSaveSous/')
        self.BtnSaveSous.CanvasBtn.bind('<ButtonRelease-1>', self.ActionSaveFileSous)
        self.BtnSaveSous.CanvasBtn.bind('<Motion>', self.MoveSaveFileSous)

        self.ImgBtnGraph, wsize, hsize, self.CanvasBtnGraph, self.ImgCanvasBtnGraph = CanInWindow(
            'Media/FrmTableur/BtnGraph/', self.RatioX, self.RatioY, self.CanvasFrmFond, int(self.SX * 0.25),
            int(self.SY * 0.057), 0)
        ChangeCursor(self.CanvasBtnGraph)

        self.ModelShow = False
        self.CanvasBtnGraph.bind('<ButtonPress-1>',
                                 lambda action: self.CanvasBtnGraph.itemconfig(self.ImgCanvasBtnGraph,
                                                                               image=self.ImgBtnGraph[1]))
        self.CanvasBtnGraph.bind('<ButtonRelease-1>', self.AffichGraph)
        self.CanvasBtnGraph.bind('<Motion>', self.MoveBtnGraph)

        self.Tableur = Tableur_Canvas(self.CanvasFrmFond, self.SX, self.SY, self.RatioX, self.RatioY, 1, 1, self)
        if self.MainAppli.MainAppli.MainAppli.AffichTabSM:
            self.ArdData = FrmArdData(self.MainAppli.MainAppli.parent, self.RatioX, self.RatioY, self)

        self.CanvasFrmFond.bind('<Motion>', self.ActionEffaceInfo)
        self.CanvasFrmFond.pack()

    def AffichNewFile(self, _):
        self.CanvasBtnNewFile.itemconfig(self.ImgCanvasBtnNewFile, image=self.ImgBtnNewFile[0])
        self.EffaceInfoAction()
        if self.ModelShow:
            self.CacheModel()
        if self.ModifTab:
            Rep = tkMB.askyesno("", "Le fichier a été modifié. Souhaitez-vous l'enregistrer ?")
            self.lift()
            if self.MainAppli.MainAppli.MainAppli.AffichTabSM:
                self.ArdData.lift()
            if Rep:
                self.SaveFile()
        self.EffaceFile()
        self.NoNewfile = self.NoNewfile + 1
        self.NameFile = "Tableur_" + str(self.NoNewfile)
        self.CanvasFrmFond.itemconfigure('LabelNameFile', text=self.NameFile)
        self.EffaceInfoAction()

    def EffaceFile(self):
        self.Tableur.destroy()
        self.Tableur = Tableur_Canvas(self.CanvasFrmFond, self.SX, self.SY, self.RatioX, self.RatioY, 1, 1, self)
        self.FileSaved = False
        self.ModifTab = False

    def MoveNewFile(self, _):
        self.AffichInfoAction('Nouveau fichier', int(self.SX * 0.3), int(self.SY * 0.057), 'black')

    def MoveOpenFile(self, _):
        self.AffichInfoAction('Ouvrir un fichier', int(self.SX * 0.3), int(self.SY * 0.057), 'black')

    def MoveSaveFile(self, _):
        self.AffichInfoAction('Enregistrer le fichier', int(self.SX * 0.3), int(self.SY * 0.057), 'black')

    def MoveSaveFileSous(self, _):
        self.AffichInfoAction('Enregistrer le fichier sous', int(self.SX * 0.3), int(self.SY * 0.057), 'black')

    def AffichInfoAction(self, Action, X, Y, color):
        if self.InfoAction:
            self.CanvasFrmFond.delete(self.TooltipAction)
            self.InfoAction = False
        self.TooltipAction = self.CanvasFrmFond.create_text(X, Y, anchor=tk.W, text=Action, fill=color,
                                                            font=FontLabel(10))
        self.InfoAction = True

    def OpenFile(self, _):
        self.CanvasBtnOpen.itemconfig(self.ImgCanvasBtnOpen, image=self.ImgBtnOpen[0])
        self.EffaceInfoAction()
        if self.ModelShow:
            self.CacheModel()
        if self.ModifTab:
            Rep = tkMB.askyesno("",
                                "Le fichier a été modifié. Souhaitez-vous l'enregistrer avant d'ouvrir un autre "
                                "fichier ?")
            if Rep:
                self.SaveFile()
        self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
            'LegendePanneauD',text='ArdPyLog - Gestionnaire de sketchs pour Arduino UNO')
        self.ChargeFile()
        self.EffaceInfoAction()

    def ChargeFile(self):
        self.FileCSV = tkfiledialog.askopenfilename(title="Ouvrir un fichier", initialdir="Sketchs/Saves/Exploit",
                                                    filetypes=[('CSV files', '.csv')])
        self.lift()
        if self.MainAppli.MainAppli.MainAppli.AffichTabSM:
            self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
                'LegendePanneauD', text="Données envoyées par l'Arduino UNO")
            self.ArdData.lift()
        try:
            if self.FileCSV != '':
                self.EffaceFile()
                RowFileCsv = []
                CsvFile = csv.reader(open(self.FileCSV, newline=''), delimiter=';')
                for line in CsvFile:
                    RowFileCsv.append(line)
                self.DatasFile = []
                for elt in RowFileCsv:
                    if RowFileCsv.index(elt) > 1:
                        ch = ''
                        for i in range(len(elt)):
                            if i < len(elt) - 1:
                                ch = ch + elt[i] + ';'
                            else:
                                ch = ch + elt[i]
                        self.DatasFile.append(ch)
                self.Tableur.AjoutDatas(self.DatasFile)
                for i in range(len(RowFileCsv[0])):
                    self.Tableur.TabLabelNCol[i]['text'] = RowFileCsv[0][i].strip()
                    self.Tableur.TabExpressCol[i] = RowFileCsv[1][i].strip()
                self.FileSaved = True
                self.ModifTab = False
                self.NameFile = ExtractNameFile(self.FileCSV)
                self.CanvasFrmFond.itemconfigure('LabelNameFile', text=self.NameFile)

        except:
            pass

    def ActionSaveFile(self, _):
        self.CanvasBtnSave.itemconfig(self.ImgCanvasBtnSave, image=self.ImgBtnSave[0])
        self.EffaceInfoAction()
        self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
            'LegendePanneauD', text='ArdPyLog - Gestionnaire de sketchs pour Arduino UNO')
        self.SaveFile()

    def ActionSaveFileSous(self, _):
        self.BtnSaveSous.CanvasBtn.itemconfig(self.BtnSaveSous.ImgCanvasBtn, image=self.BtnSaveSous.ImgBtn[0])
        self.EffaceInfoAction()
        self.FileSaved = False
        self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
            'LegendePanneauD', text='ArdPyLog - Gestionnaire de sketchs pour Arduino UNO')
        self.SaveFile()

    def SaveFile(self):
        if not self.FileSaved:
            self.FileCSV = tkfiledialog.asksaveasfilename(title="Enregistrer sous", filetypes=[('CSV files', '.csv')],
                                                          initialfile=self.NameFile, initialdir="Sketchs/Saves/Exploit",
                                                          defaultextension='.csv')
            self.lift()
            if self.MainAppli.MainAppli.MainAppli.AffichTabSM:
                self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
                    'LegendePanneauD', text="Données envoyées par l'Arduino UNO")
                self.ArdData.lift()
            try:
                if self.FileCSV != '':
                    self.EnregistreFile(self.FileCSV)
                    self.FileSaved = True
                    self.ModifTab = False
                    self.NameFile = ExtractNameFile(self.FileCSV)
                    self.CanvasFrmFond.itemconfigure('LabelNameFile', text=self.NameFile)
            except:
                pass
        else:
            self.EnregistreFile(self.FileCSV)
            self.ModifTab = False
        self.EffaceInfoAction()

    def EnregistreFile(self, File):
        csvfile = open(File, 'w', newline='')
        SaveWriter = csv.writer(csvfile, delimiter=';')
        ValC = []
        ValExpress = []
        for j in range(self.Tableur.NCol - 1):
            ValC.append(self.Tableur.TabLabelNCol[j]['text'])
            ValExpress.append(self.Tableur.TabExpressCol[j])
        SaveWriter.writerow(ValC)
        SaveWriter.writerow(ValExpress)
        for i in range(self.Tableur.Npoint):
            ValC = []
            for j in range(self.Tableur.NCol - 1):
                if self.Tableur.TabLabels[i][j]['text'] != '':
                    ValC.append(self.Tableur.TabLabels[i][j]['text'])
            SaveWriter.writerow(ValC)

        csvfile.close()

    def MoveBtnGraph(self, _):
        self.AffichInfoAction('Afficher le graphe', int(self.SX * 0.3), int(self.SY * 0.057), 'black')

    def ActionEffaceInfo(self, _):
        self.EffaceInfoAction()

    def EffaceInfoAction(self):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        if self.InfoAction:
            self.CanvasFrmFond.delete(self.TooltipAction)
            self.InfoAction = False

    def AffichGraph(self, _):
        self.CanvasBtnGraph.itemconfig(self.ImgCanvasBtnGraph, image=self.ImgBtnGraph[0])
        self.EffaceInfoAction()
        if self.Tableur.Npoint > 0:
            self.Graph = FrmGraph(self.MainAppli.MainAppli.parent, self.RatioX, self.RatioY, self)
            self.ParaGraph = FrmParaGraph(self.MainAppli.MainAppli.parent, self.RatioX, self.RatioY, self)

    def CacheFrmTableur(self, _):
        self.ActionCacheFrmTableur()

    def ActionCacheFrmTableur(self):
        if self.ModifTab:
            Rep = tkMB.askyesno("",
                                "Le fichier a été modifié. Souhaitez-vous l'enregistrer avant de fermer la fenêtre ?")
            if Rep:
                self.SaveFile()
        if self.ParaTab:
            self.Tableur.ParaTab.Fermer()
        self.Tableur.destroy()
        if self.MainAppli.MainAppli.MainAppli.AffichCode:
            self.MainAppli.MainAppli.MainAppli.FrmCode.lift(self.MainAppli.MainAppli.MainAppli.parent)
        elif self.MainAppli.MainAppli.MainAppli.AffichDescript:
            self.MainAppli.MainAppli.MainAppli.FrmDescrip.lift(self.MainAppli.MainAppli.MainAppli.parent)
        elif self.MainAppli.MainAppli.MainAppli.AffichDoc:
            self.MainAppli.MainAppli.MainAppli.FrmDoc.lift(self.MainAppli.MainAppli.MainAppli.parent)
        self.destroy()
        if self.MainAppli.MainAppli.MainAppli.AffichTabSM:
            self.MainAppli.MainAppli.MainAppli.LPDText = 'ArdPyLog - Gestionnaire de sketchs pour Arduino UNO'
            self.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                           text=self.MainAppli.MainAppli.MainAppli.
                                                                           LPDText)
            self.MainAppli.MainAppli.MainAppli.parent.lift()
            self.ArdData.destroy()
            self.MainAppli.AffichTab = False
            self.MainAppli.MainAppli.MainAppli.AffichTabSM = False
            self.MainAppli.lift()
        elif self.MainAppli.MainAppli.MainAppli.ModeAcquisitionActif:
            self.MainAppli.ActionCacheFrmSerialMonitor()
            self.MainAppli.MainAppli.MainAppli.FrmINO.destroy()
            self.MainAppli.MainAppli.MainAppli.FrmAcqui.lift()
            self.MainAppli.MainAppli.MainAppli.FrmAcqui.TableurAcqui.lift()
        else:
            self.MainAppli.MainAppli.MainAppli.parent.lift()
            self.MainAppli.ActionCacheFrmSerialMonitor()
            self.MainAppli.MainAppli.MainAppli.FrmINO.destroy()
            self.MainAppli.MainAppli.MainAppli.GoHome = True
            self.MainAppli.MainAppli.MainAppli.FrmLift()
        self.MainAppli.MainAppli.MainAppli.AffichTab = False
        self.MainAppli.MainAppli.MainAppli.CanvasEtagCircuits.itemconfig(
            self.MainAppli.MainAppli.MainAppli.ImgCanvasEtagCircuits,
            image=self.MainAppli.MainAppli.MainAppli.ImgEtagCircuits[1])

    def ShowWarning(self, text1, text2):
        tkMB.showwarning(text1, text2)
        self.lift()
        self.Tableur.ActionModifVar()


class Tableur_Canvas(tk.Canvas):
    def __init__(self, conteneur, SX, SY, Ratio, Ratio2, NLine, NCol, Appli):

        self.MainAppli = Appli
        self.FileSaved = False
        self.InfoAction = False
        self.FileCSV = None
        self.TooltipAction = None
        self.ParaTab = None
        self.MatriceData = None
        self.EntryManuelVal = None
        self.Varlist = []
        self.NCol = NCol
        self.NLine = NLine
        self.SX = SX
        self.RatioX = Ratio
        self.RatioY = Ratio2
        self.TypeAction = ''
        self.ActionInfo = ['Ajouter les données', 'Effacer les données',
                           'Ajouter une variable', 'Ajouter une ligne de données']
        self.VarAModif = 0
        self.NameCol = []
        self.CoordModifPoint = [-1, -1]
        self.Kol = 0
        self.LineSelected = 0

        self.ImgFond = Image.open('Media/FrmTableur/Tableur/Fond/01.jpg')
        self.ListImgFond = RedimImg(int(self.ImgFond.size[0] * Ratio),
                                    int(self.ImgFond.size[1] * Ratio2), 'Media/FrmTableur/Tableur/Fond/')
        tk.Canvas.__init__(self, conteneur, width=int(self.ImgFond.size[0] * Ratio),
                           height=int(self.ImgFond.size[1] * Ratio2), highlightthickness=0, bd=0)
        conteneur.create_window(int(SX * 0.5), int(SY * 0.538), anchor=tk.CENTER, window=self)
        self.create_image(0, 0, anchor=tk.NW, image=self.ListImgFond[0])

        self.CanTabWidth = int(self.ImgFond.size[0] * Ratio)
        self.CanTabHeight = int(self.ImgFond.size[1] * Ratio2)
        self.Npoint = 0

        self.bind('<Motion>', self.ActionEffaceInfo)
        self.bind('<Button-1>', self.UnSelect)

        self.FrameTableur = tk.Frame(self)
        self.create_window(int(self.CanTabWidth / 2), int(self.CanTabHeight * 0.535), anchor=tk.CENTER,
                           window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(self.CanTabWidth * 0.95),
                                                  int(self.CanTabHeight * 0.9))
        self.scrollable_canvas.grid(row=1, column=1)

        tk.Label(self.scrollable_canvas.interior, text='', relief=tk.FLAT, width=int(SX * 0.005), bg='white',
                 font=FontLabel2(10)).grid(row=0, column=0)

        self.TabLabelNCol = []
        self.TabExpressCol = []
        self.TabLabelNColSelected = []
        self.TabLabelN = []
        self.TabLabelNSelected = []
        self.TabLabelCol = []
        self.TabLabels = []

        self.ListBtn = []
        self.ImgBtnNewPoint, wsize, hsize, self.CanvasBtnNewPoint, self.ImgCanvasBtnNewPoint = CanInWindow(
            'Media/FrmTableur/Tableur/BtnNewPoint/', Ratio, Ratio2, self, int(self.CanTabWidth * 0.22),
            int(self.CanTabHeight * 0.032), 0)
        ChangeCursor(self.CanvasBtnNewPoint)
        self.CanvasBtnNewPoint.bind('<ButtonRelease-1>', self.ActionAjoutDatas)
        self.ListBtn.append(self.CanvasBtnNewPoint)

        self.LegNPoint = self.create_text(int(self.CanTabWidth * 0.03), int(self.CanTabHeight * 0.032),
                                          text='', font=FontLabel2(12))
        self.addtag_withtag('LegNPoint', self.LegNPoint)

        self.EntryValPoint = tk.Entry(self, text='', width=int(self.SX * 0.01), font=FontLabel(14), justify='right')
        self.create_window(int(self.CanTabWidth * 0.12), int(self.CanTabHeight * 0.032), anchor=tk.CENTER,
                           window=self.EntryValPoint)

        def GestEvt2(evt):
            return self.EvtAjoutManuelData(evt)

        self.EntryValPoint.bind('<Return>', GestEvt2)
        self.EntryValPoint.bind('<KeyRelease>', self.ChangeEntryManuelVal)

        self.ImgBtnEffacePoint, wsize, hsize, self.CanvasBtnEffacePoint, self.ImgCanvasBtnEffacePoint = CanInWindow(
            'Media/FrmTableur/Tableur/BtnEffacerPoint/', Ratio, Ratio2, self, int(self.CanTabWidth * 0.27),
            int(self.CanTabHeight * 0.032), 0)
        ChangeCursor(self.CanvasBtnEffacePoint)
        self.CanvasBtnEffacePoint.bind('<ButtonRelease-1>', self.EffaceDatas)
        self.ListBtn.append(self.CanvasBtnEffacePoint)

        self.BtnAjoutCol = BtnAction(self, int(self.CanTabWidth * 0.32), int(self.CanTabHeight * 0.032), Ratio,
                                     Ratio2, 'Media/FrmTableur/Tableur/BtnAjoutCol/')
        self.BtnAjoutCol.CanvasBtn.bind('<ButtonRelease-1>', self.AjoutNewCol)
        self.ListBtn.append(self.BtnAjoutCol.CanvasBtn)

        self.BtnAjoutLine = BtnAction(self, int(self.CanTabWidth * 0.37), int(self.CanTabHeight * 0.032), Ratio,
                                      Ratio2, 'Media/FrmTableur/Tableur/BtnAjoutLine/')
        self.ListBtn.append(self.BtnAjoutLine.CanvasBtn)

        def GestEvt3(evt):
            return self.AjoutPoint(evt, self.Npoint)

        self.BtnAjoutLine.CanvasBtn.bind('<ButtonRelease-1>', GestEvt3)

        for i in range(len(self.ListBtn)):
            def GestEvt(evt, j=i):
                return self.MoveOnBtn(evt, j)

            self.ListBtn[i].bind('<Motion>', GestEvt)

        self.AffichTab(NLine, NCol)
        self.MAJMatrice()

    def AjoutLine(self, NLine):
        for r in range(self.NLine + 1, self.NLine + NLine + 1):
            self.TabLabelN.append(tk.Label(self.scrollable_canvas.interior, text=str(r), relief=tk.RIDGE,
                                           width=int(self.SX * 0.005), bg='white', font=FontLabel2(10)))
            self.TabLabelN[r - 1].grid(row=r, column=0)
            self.TabLabelNSelected.append(False)
            ChangeCursor(self.TabLabelN[r - 1])

            def GestEvt(evt, j=r - 1):
                return self.SelectLine(evt, j)

            def GestEvt2(evt, j=r - 1):
                return self.AjoutPoint(evt, j)

            self.TabLabelN[r - 1].bind('<Button-1>', GestEvt)
            self.TabLabelN[r - 1].bind('<Double-1>', GestEvt2)

            self.TabLabelCol = []
            for i in range(self.NCol):
                self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                 width=int(self.SX * 0.013), bg='white', font=FontLabel(12)))
                self.TabLabelCol[i].grid(row=r, column=i + 1)

            self.TabLabels.append(self.TabLabelCol)
        self.NLine = self.NLine + NLine
        self.DoubleClicTab()

    def AjoutCol(self, NCol):
        for i in range(self.NCol, self.NCol + NCol):
            self.NameCol.append(chr(i + 65))
            self.TabLabelNCol.append(tk.Label(self.scrollable_canvas.interior, text=self.NameCol[i], relief=tk.RIDGE,
                                              width=int(self.SX * 0.013), bg='white', font=FontLabel2(11)))
            self.TabLabelNCol[i].grid(row=0, column=i + 1)
            self.TabLabelNColSelected.append(False)
            self.TabExpressCol.append('')
            ChangeCursor(self.TabLabelNCol[i])

            def GestEvt(evt, j=i):
                return self.SelectCol(evt, j)

            def GestEvt2(evt, j=i):
                return self.ModifVar(evt, j)

            self.TabLabelNCol[i].bind('<Button-1>', GestEvt)
            self.TabLabelNCol[i].bind('<Double-1>', GestEvt2)

        self.NCol = self.NCol + NCol
        self.TabLabels = []
        for r in range(1, self.NLine + 1):
            self.TabLabelCol = []
            for i in range(self.NCol):
                self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                 width=int(self.SX * 0.013), bg='white', font=FontLabel(12)))
                self.TabLabelCol[i].grid(row=r, column=i + 1)
            self.TabLabels.append(self.TabLabelCol)
        self.DoubleClicTab()

    def DoubleClicTab(self):
        for l in range(self.NLine):
            for k in range(self.NCol):
                def GestEvt(evt, i=l, j=k):
                    return self.ModifPoint(evt, i, j)

                self.TabLabels[l][k].bind('<Double-1>', GestEvt)
                self.TabLabels[l][k].bind('<Button-1>', self.UnSelect)

    def AjoutMatriceCol(self):
        NewCol = []
        for i in range(self.Npoint):
            NewCol.append(0)
        NewMatriceCol = np.array(NewCol)
        self.MatriceData = np.c_[self.MatriceData, NewMatriceCol]

    def AjoutNewCol(self, _):
        self.BtnAjoutCol.CanvasBtn.itemconfig(self.BtnAjoutCol.ImgCanvasBtn, image=self.BtnAjoutCol.ImgBtn[0])
        if self.TypeAction == '':
            self.TypeAction = 'AjoutVar'
            self.VarAModif = self.NCol - 1
            self.ActionModifVar()

    def ModifPoint(self, _, i, j):
        if i != self.NLine - 1 and j != self.NCol - 1 and self.TypeAction == '':
            if self.CoordModifPoint[0] != -1:
                self.ActionValidModifPoint(self.CoordModifPoint[0], self.CoordModifPoint[1])
                self.CoordModifPoint = [-1, -1]
            self.CoordModifPoint = [i, j]
            self.EntryManuelVal = tk.Entry(self.scrollable_canvas.interior, text='', width=int(self.SX * 0.013),
                                           font=FontLabel(12), justify='right')
            self.EntryManuelVal.grid(row=i + 1, column=j + 1)
            self.EntryManuelVal.insert(0, self.TabLabels[i][j]['text'])
            self.EntryValPoint.insert(0, self.TabLabels[i][j]['text'])
            self.EntryManuelVal.focus_set()
            self.itemconfigure('LegNPoint', text=str(i + 1))

            def GestEvt(evt):
                return self.ValidModifPoint(evt, i, j)

            self.EntryManuelVal.bind('<Return>', GestEvt)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ValidModifPoint(self, _, i, j):
        self.ActionValidModifPoint(i, j)

    def ActionValidModifPoint(self, i, j):
        if self.EntryManuelVal.get() != '':
            try:
                float(self.EntryManuelVal.get().replace(",", "."))
            except:
                self.MainAppli.ShowWarning('Attention', "La donnée ne doit contenir que des caractères numériques !")
                self.EntryManuelVal.delete(0, 'end')
                self.EntryValPoint.delete(0, 'end')
                self.EntryManuelVal.focus_set()
                return
            else:
                self.TabLabels[i][j]['text'] = self.EntryManuelVal.get()
        else:
            self.TabLabels[i][j]['text'] = '0'

        self.EntryManuelVal.grid_forget()
        self.EntryManuelVal = None
        self.EntryValPoint.delete(0, 'end')
        self.MAJDatas()
        self.CoordModifPoint = [-1, -1]

    def AjoutPoint(self, _, j):
        self.BtnAjoutLine.CanvasBtn.itemconfig(self.BtnAjoutLine.ImgCanvasBtn, image=self.BtnAjoutLine.ImgBtn[0])
        if self.NCol == 1:
            self.AjoutCol(1)
        self.Kol = 1
        self.ActionAjoutPoint(j, 1)

    def ActionAjoutPoint(self, j, k):
        self.LineSelected = j
        self.EntryManuelVal = tk.Entry(self.scrollable_canvas.interior, text='', width=int(self.SX * 0.013),
                                       font=FontLabel(12), justify='right')
        self.EntryManuelVal.grid(row=j + 1, column=k)
        self.EntryManuelVal.focus_set()
        self.EntryManuelVal.bind('<KeyRelease>', self.ChangeValEntryPoint)

        def GestEvt(evt):
            return self.ValidPoint(evt, j, k)

        self.EntryManuelVal.bind('<Return>', GestEvt)

    def ValidPoint(self, _, j, k):
        self.ActionValidPoint(j, k)

    def ActionValidPoint(self, j, k):
        if self.EntryManuelVal.get() != '':
            try:
                float(self.EntryManuelVal.get().replace(",", "."))
            except:
                self.MainAppli.ShowWarning('Attention', "La donnée ne doit contenir que des caractères numériques !")
                self.EntryManuelVal.delete(0, 'end')
                self.EntryValPoint.delete(0, 'end')
                self.EntryManuelVal.focus_set()
                return
            else:
                self.TabLabels[j][k - 1]['text'] = self.EntryManuelVal.get()
        else:
            self.TabLabels[j][k - 1]['text'] = '0'
        self.EntryValPoint.delete(0, 'end')
        self.EntryManuelVal.grid_forget()
        self.EntryManuelVal = None
        Kol = k
        while self.TabExpressCol[Kol] != '':
            if (Kol + 1) != self.NCol:
                Kol = Kol + 1
            else:
                break
        if (Kol + 1) != self.NCol:
            self.Kol = Kol + 1
            self.ActionAjoutPoint(j, Kol + 1)
        else:
            if j == self.NLine - 1:
                self.AjoutLine(1)
                self.Npoint = self.Npoint + 1
            self.MAJDatas()
            self.focus_set()
            self.Kol = 1

    def ChangeValEntryPoint(self, _):
        self.EntryValPoint.delete(0, 'end')
        self.EntryValPoint.insert(0, self.EntryManuelVal.get())

    def ChangeEntryManuelVal(self, _):
        if self.EntryManuelVal is not None:
            self.EntryManuelVal.delete(0, 'end')
            self.EntryManuelVal.insert(0, self.EntryValPoint.get())

    def ModifVar(self, _, j):
        self.VarAModif = j
        self.ActionUnSelect()
        self.ActionSelectCol(j)
        if self.TypeAction != '':
            self.ParaTab.Fermer()
        if self.VarAModif != self.NCol - 1:
            self.TypeAction = 'ModifVar'
        else:
            self.TypeAction = 'AjoutVar'
        self.ActionModifVar()

    def ActionModifVar(self):
        self.ParaTab = FrmParaTab(self.MainAppli.MainAppli.MainAppli.parent, self.RatioX, self.RatioY, self)

    def ActionAjoutDatas(self, _):
        if self.MainAppli.MainAppli.MainAppli.MainAppli.AffichTabSM:
            if self.EntryValPoint.get() == '' and self.EntryManuelVal is None:
                data = []
                for i in range(len(self.MainAppli.ArdData.ListLine)):
                    data.append(self.MainAppli.ArdData.ListBoxData.get(self.MainAppli.ArdData.ListLine[i]))
                self.AjoutDatas(data)
            elif self.EntryValPoint.get() != '':
                if self.EntryManuelVal is None:
                    self.AjoutManuelData(0)
                else:
                    if self.CoordModifPoint[0] != -1:
                        self.ActionValidModifPoint(self.CoordModifPoint[0], self.CoordModifPoint[1])
                    else:
                        self.ActionValidPoint(self.LineSelected, self.Kol)
        elif self.EntryValPoint.get() != '':
            if self.EntryManuelVal is None:
                self.AjoutManuelData(0)
            else:
                if self.CoordModifPoint[0] != -1:
                    self.ActionValidModifPoint(self.CoordModifPoint[0], self.CoordModifPoint[1])
                else:
                    self.ActionValidPoint(self.LineSelected, self.Kol)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def EvtAjoutManuelData(self, _):
        if self.EntryManuelVal is None:
            self.AjoutManuelData(0)
        else:
            if self.CoordModifPoint[0] != -1:
                self.ActionValidModifPoint(self.CoordModifPoint[0], self.CoordModifPoint[1])
            else:
                self.ActionValidPoint(self.Npoint, self.Kol)

    def AjoutManuelData(self, k):
        if self.EntryValPoint.get() != '':
            try:
                float(self.EntryValPoint.get().replace(",", "."))
            except:
                self.MainAppli.ShowWarning('Attention', "La donnée ne doit contenir que des caractères numériques !")
                self.EntryValPoint.delete(0, 'end')
                self.EntryValPoint.focus_set()
                return
            else:
                if self.NCol == 1:
                    self.AjoutCol(1)
                self.TabLabels[self.Npoint][k]['text'] = self.EntryValPoint.get().replace(".", ",")
        else:
            if self.NCol == 1:
                self.AjoutCol(1)
            self.TabLabels[self.Npoint][k]['text'] = '0'
        self.EntryValPoint.delete(0, 'end')
        Kol = k + 1
        while self.TabExpressCol[Kol] != '':
            if (Kol + 1) != self.NCol:
                Kol = Kol + 1
            else:
                break
        if (Kol + 1) != self.NCol:
            self.Kol = Kol + 1
            self.ActionAjoutPoint(self.Npoint, Kol + 1)
        else:
            self.AjoutLine(1)
            self.Npoint = self.Npoint + 1
            self.MAJDatas()

    def AjoutDatas(self, Datalist):
        if self.Npoint == 0:
            self.EffaceTableau()
        if len(Datalist) >= self.NLine - self.Npoint:
            self.AjoutLine(len(Datalist) - self.NLine + self.Npoint + 1)
        for i in range(len(Datalist)):
            ch = Datalist[i]
            listch = ch.split(';')
            if len(listch) >= self.NCol:
                self.AjoutCol(len(listch) - self.NCol + 1)
            for j in range(len(listch)):
                self.TabLabels[self.Npoint][j].config(text=listch[j].strip().replace(".", ","))
            self.Npoint = self.Npoint + 1
        self.MAJDatas()

    def MAJDatas(self):
        self.itemconfigure('LegNPoint', text=str(self.Npoint + 1))
        for i in range(len(self.TabLabelN)):
            self.TabLabelN[i].config(bg='white')
        self.TabLabelN[self.Npoint].config(bg='#E0E0E0')
        self.ActionUnSelect()
        self.MainAppli.ModifTab = True
        self.MAJMatrice()
        self.MAJListVar()
        self.MAJCalculDatas()
        self.AffichMatriceData()

    def EffaceDatas(self, _):
        if self.Npoint > 0:
            self.ActionEffaceDatas()
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ActionEffaceDatas(self):
        for i in range(self.NLine):
            if self.TabLabelNSelected[i] and i < self.NLine - 1:
                self.Npoint = self.Npoint - 1
                for j in range(self.NCol):
                    self.TabLabels[i][j].config(text='')
                self.TabLabelNSelected[i] = False
                self.MainAppli.ModifTab = True
                self.NLine = self.NLine - 1

        for i in range(self.NLine - 1):
            if self.TabLabels[i][0]['text'] == '':
                ni = i
                nl = i + 1
                while self.TabLabels[nl][0]['text'] == '':
                    nl = nl + 1
                    if nl >= self.NLine - 1:
                        break
                compt = 0
                for l in range(nl, self.NLine):
                    for j in range(self.NCol):
                        self.TabLabels[ni + compt][j].config(text=self.TabLabels[nl][j]['text'])
                    nl = nl + 1
                    compt = compt + 1

        for i in range(self.NCol):
            if self.TabLabelNColSelected[i] and i < self.NCol - 1:
                for l in range(self.NLine):
                    for c in range(i, self.NCol - 1):
                        self.TabLabels[l][c].config(text=self.TabLabels[l][c + 1]['text'])
                self.TabLabelNColSelected[i] = False
                for c in range(i, self.NCol - 1):
                    self.TabLabelNCol[c]['text'] = self.TabLabelNCol[c + 1]['text']
                    self.TabExpressCol[c] = self.TabExpressCol[c + 1]
                    self.VerifColVide(c)
                self.NCol = self.NCol - 1
                self.MainAppli.ModifTab = True

        if self.Npoint > 0:
            NewTabLabels = []
            for i in range(self.NLine):
                TabLabelCol = []
                for k in range(self.NCol):
                    TabLabelCol.append(self.TabLabels[i][k])
                NewTabLabels.append(TabLabelCol)
            self.TabLabels = []
            self.TabLabels = list(NewTabLabels)
            self.MAJMatrice()
            self.MAJListVar()
            self.MAJCalculDatas()
            NLine = self.NLine
            NCol = self.NCol
            Npoint = self.Npoint
            TabLabelNCol = []
            for i in range(NCol):
                TabLabelNCol.append(self.TabLabelNCol[i]['text'])
            TabExpressCol = list(self.TabExpressCol)
            self.EffaceTableau()
            self.AffichTab(NLine, NCol)
            self.TabExpressCol = TabExpressCol
            for i in range(NCol):
                self.TabLabelNCol[i]['text'] = TabLabelNCol[i]
            self.Npoint = Npoint
            self.AffichMatriceData()
            self.TabLabelN[0].config(bg='white')
            self.TabLabelN[self.Npoint].config(bg='#E0E0E0')
            self.itemconfigure('LegNPoint', text=str(self.Npoint + 1))
        else:
            self.EffaceTableau()
            self.AffichTab(1, 1)

    def MoveOnBtn(self, _, j):
        self.AffichInfoAction(self.ActionInfo[j], int(self.CanTabWidth * 0.4), int(self.CanTabHeight * 0.032), 'black')

    def AffichInfoAction(self, Action, X, Y, color):
        if self.InfoAction:
            self.delete(self.TooltipAction)
            self.InfoAction = False
        self.TooltipAction = self.create_text(X, Y, anchor=tk.W, text=Action, fill=color, font=FontLabel2(10))
        self.InfoAction = True

    def ActionEffaceInfo(self, _):
        self.EffaceInfoAction()

    def EffaceInfoAction(self):
        self.MainAppli.EffaceInfoAction()
        if self.InfoAction:
            self.delete(self.TooltipAction)
            self.InfoAction = False

    def SelectLine(self, _, j):
        self.ActionUnSelect()
        self.TabLabelN[self.Npoint].config(bg='white')
        self.itemconfigure('LegNPoint', text=str(j + 1))
        if not self.TabLabelNSelected[j]:
            self.TabLabelNSelected[j] = True
            self.TabLabelN[j].config(bg='#E0E0E0')
            for i in range(self.NCol):
                self.TabLabels[j][i].config(bg='#E0E0E0')
        else:
            self.TabLabelN[j].config(bg='white')
            for i in range(self.NCol):
                self.TabLabels[j][i].config(bg='white')
            self.TabLabelNSelected[j] = False
            notselected = True
            for i in range(self.Npoint):
                if self.TabLabelNSelected[i]:
                    self.itemconfigure('LegNPoint', text=str(i + 1))
                    notselected = False
                    break
            if notselected:
                self.TabLabelN[self.Npoint].config(bg='#E0E0E0')
                self.itemconfigure('LegNPoint', text=str(self.Npoint + 1))

    def ActionUnSelect(self):
        for i in range(self.NLine):
            self.TabLabelN[i].config(bg='white')
            self.TabLabelNSelected[i] = False
            for j in range(self.NCol):
                self.TabLabelNCol[j].config(bg='white')
                self.TabLabelNColSelected[j] = False
                self.TabLabels[i][j].config(bg='white')
        self.TabLabelN[self.Npoint].config(bg='#E0E0E0')

    def UnSelect(self, _):
        self.ActionUnSelect()

    def SelectCol(self, _, j):
        if self.TypeAction == '':
            self.ActionSelectCol(j)

    def ActionSelectCol(self, j):
        self.ActionUnSelect()
        if not self.TabLabelNColSelected[j]:
            bgcolor = '#E0E0E0'
            self.TabLabelNColSelected[j] = True
        else:
            bgcolor = 'white'
            self.TabLabelNColSelected[j] = False
        self.TabLabelNCol[j].config(bg=bgcolor)
        for i in range(self.NLine):
            self.TabLabels[i][j].config(bg=bgcolor)

    def VerifColVide(self, Ncol):
        vide = True
        for i in range(self.NLine):
            if self.TabLabels[i][Ncol]['text'] != '':
                vide = False
        if vide:
            self.TabLabelNCol[Ncol]['text'] = self.NameCol[Ncol]

    def MAJMatrice(self):
        self.MatriceData = np.empty((self.Npoint, self.NCol - 1))
        for i in range(self.Npoint):
            for j in range(self.NCol - 1):
                if self.TabLabels[i][j]['text'] != '':
                    try:
                        self.MatriceData[i, j] = float(self.TabLabels[i][j]['text'].replace(",", "."))
                    except:
                        self.MatriceData[i, j] = 0
                else:
                    self.MatriceData[i, j] = 0

    def MAJCalculDatas(self):
        for j in range(self.NCol - 1):
            if self.TabExpressCol[j] != '':
                ListVar = vars()
                for l in range(self.Npoint):
                    for c in range(self.NCol - 1):
                        ListVar[self.Varlist[c]] = self.MatriceData[l, c]
                    try:
                        self.MatriceData[l, j] = eval(self.TabExpressCol[j])

                    except:
                        pass

    def MAJListVar(self):
        self.Varlist = []
        for i in range(self.NCol - 1):
            NameVar = self.TabLabelNCol[i]['text'].split(' (')
            self.Varlist.append(NameVar[0].strip())

    def CalculDatas(self, Ncol):
        ListVar = vars()
        for i in range(self.Npoint):
            for j in range(self.NCol - 1):
                ListVar[self.Varlist[j]] = self.MatriceData[i, j]
            if self.ParaTab.EntryExpress.get() != '' and self.ParaTab.EntryExpress.get() != ' ':
                self.TabExpressCol[Ncol] = self.ParaTab.EntryExpress.get().replace(" ", "")
                try:
                    self.MatriceData[i, Ncol] = eval(self.TabExpressCol[Ncol])
                except:
                    self.MatriceData[i, Ncol] = 0

    def AffichMatriceData(self):
        for i in range(self.Npoint):
            for j in range(self.NCol - 1):
                if self.MatriceData[i, j] > 0.01 or self.MatriceData[i, j] == 0:
                    self.TabLabels[i][j]['text'] = str(round(self.MatriceData[i, j],3)).replace(".", ",")
                else:
                    self.TabLabels[i][j]['text'] = format(self.MatriceData[i, j], ".2E").replace(".", ",")

    def EffaceTableau(self):
        for elt in self.scrollable_canvas.interior.winfo_children():
            elt.destroy()
        self.TabLabels = []
        self.TabLabelN = []
        self.TabLabelNCol = []
        self.NCol = 0
        self.NLine = 0
        self.NameCol = []
        self.Npoint = 0

    def AffichTab(self, NLine, NCol):
        self.NameCol = []
        for i in range(NCol):
            self.NameCol.append(chr(i + 65))
        self.TabLabelNCol = []
        self.TabExpressCol = []
        self.TabLabelNColSelected = []
        self.NCol = NCol
        self.NLine = NLine
        self.Npoint = 0

        for i in range(NCol):
            self.TabLabelNCol.append(tk.Label(self.scrollable_canvas.interior, text=self.NameCol[i], relief=tk.RIDGE,
                                              width=int(self.SX * 0.013), bg='white', font=FontLabel2(11)))
            self.TabLabelNCol[i].grid(row=0, column=i + 1)
            self.TabLabelNColSelected.append(False)
            self.TabExpressCol.append('')
            ChangeCursor(self.TabLabelNCol[i])

            def GestEvt(evt, j=i):
                return self.SelectCol(evt, j)

            def GestEvt2(evt, j=i):
                return self.ModifVar(evt, j)

            self.TabLabelNCol[i].bind('<Button-1>', GestEvt)
            self.TabLabelNCol[i].bind('<Double-1>', GestEvt2)

        self.TabLabelN = []
        self.TabLabelNSelected = []
        self.TabLabels = []

        for r in range(1, NLine + 1):
            self.TabLabelN.append(tk.Label(self.scrollable_canvas.interior, text=str(r), relief=tk.RIDGE,
                                           width=int(self.SX * 0.005), bg='white', font=FontLabel2(10)))
            self.TabLabelN[r - 1].grid(row=r, column=0)
            self.TabLabelNSelected.append(False)
            ChangeCursor(self.TabLabelN[r - 1])

            def GestEvt3(evt, j=r - 1):
                return self.SelectLine(evt, j)

            def GestEvt4(evt, j=r - 1):
                return self.AjoutPoint(evt, j)

            self.TabLabelN[r - 1].bind('<Button-1>', GestEvt3)
            self.TabLabelN[r - 1].bind('<Double-1>', GestEvt4)

            self.TabLabelCol = []
            for i in range(NCol):
                self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                 width=int(self.SX * 0.013), bg='white', font=FontLabel(12)))
                self.TabLabelCol[i].grid(row=r, column=i + 1)

            self.TabLabels.append(self.TabLabelCol)

            for k in range(NCol):
                def GestEvt5(evt, l=r - 1, j=k):
                    return self.ModifPoint(evt, l, j)

                self.TabLabels[r - 1][k].bind('<Button-1>', self.UnSelect)
                self.TabLabels[r - 1][k].bind('<Double-1>', GestEvt5)

        self.TabLabelN[self.Npoint].config(bg='#E0E0E0')
        self.itemconfigure('LegNPoint', text=str(self.Npoint + 1))


class FrmArdData(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.ListLine = []
        self.IndexLine = 0

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmTableur/Data/Fond/Fond.bmp')
        self.SX = int((float(FrmFond.size[0]) * float(RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmTableur/Data/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.753)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.11)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.ScrollbarListBoxV = tk.Scrollbar(self.CanvasFrmFond)
        self.ScrollbarListBoxV.pack(side=tk.RIGHT, fill=tk.Y)
        self.ListBoxData = tk.Listbox(self.CanvasFrmFond, width=self.SX, height=self.SY,
                                      activestyle='none', selectmode='extended')
        self.ListBoxData.config(yscrollcommand=self.ScrollbarListBoxV.set)
        self.ScrollbarListBoxV.config(command=self.ListBoxData.yview)

        self.ScrollbarListBoxH = tk.Scrollbar(self.CanvasFrmFond, orient=tk.HORIZONTAL)
        self.ScrollbarListBoxH.pack(side=tk.BOTTOM, fill=tk.X)
        self.ListBoxData.config(xscrollcommand=self.ScrollbarListBoxH.set)
        self.ScrollbarListBoxH.config(command=self.ListBoxData.xview)

        self.ListBoxData.bind('<<ListboxSelect>>', self.OnSelectListBoxData)
        self.ListBoxData.pack()

        ArData = self.MainAppli.MainAppli.ZoneTextSM.get(0.0, tk.END)
        FileToSave = open('Sketchs/Saves/Datas/ArData.txt', "w", encoding="utf-8")
        FileToSave.write(ArData)
        FileToSave.close()

        Fichier = open('Sketchs/Saves/Datas/ArData.txt', "r", encoding="utf-8")
        for line in Fichier:
            self.ListBoxData.insert(tk.END, line)
        Fichier.close()

        self.LPDText = "Données envoyées par l'Arduino UNO"
        self.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD', text=self.LPDText)
        self.MainAppli.MainAppli.MainAppli.MainAppli.LPDText = self.LPDText

        self.CanvasFrmFond.pack()

    def OnSelectListBoxData(self, evt):
        try:
            w = evt.widget
            self.ListLine = []
            for i in range(len(w.curselection())):
                self.IndexLine = int(w.curselection()[i])
                if self.IndexLine not in self.ListLine:
                    self.ListLine.append(self.IndexLine)
        except:
            pass


class FrmParaTab(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.NColPrec = 0
        self.LPDText = ''
        self.NomVar = ''
        self.ChangeNameVar = False

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmTableur/Data/Fond/Fond.bmp')
        self.SX = int((float(FrmFond.size[0]) * float(RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(RatioY)))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmTableur/Data/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.753)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.11)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                           text="Tableur - Paramètres")
        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.Nconfig, 'TP'))

        self.LabelTitre = LabelInCanvas(self.CanvasFrmFond, 'Ajouter une variable', '#F7F7F7', FontLabelTitre(SizeFont),
                                        int(self.SX * 0.05), int(self.SY * 0.02))

        self.LabelNom = LabelInCanvas(self.CanvasFrmFond, '. Nom :', '#F7F7F7', FontLabel(SizeFont),
                                      int(self.SX * 0.08), int(self.SY * 0.08))
        self.EntryNom = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.08), font=FontLabel2(SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.25), int(self.SY * 0.08), anchor=tk.NW, window=self.EntryNom)

        self.LabelUnit = LabelInCanvas(self.CanvasFrmFond, '. Unité :', '#F7F7F7', FontLabel(SizeFont),
                                       int(self.SX * 0.08), int(self.SY * 0.14))
        self.EntryUnit = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.08), font=FontLabel2(SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.25), int(self.SY * 0.14), anchor=tk.NW, window=self.EntryUnit)

        self.LabelExpress = LabelInCanvas(self.CanvasFrmFond, '. Expression mathématique :', '#F7F7F7',
                                          FontLabel(SizeFont), int(self.SX * 0.08), int(self.SY * 0.20))
        self.LabelExpress2 = LabelInCanvas(self.CanvasFrmFond, '', '#F7F7F7', FontLabel2(SizeFont), int(self.SX * 0.08),
                                           int(self.SY * 0.24))
        self.EntryExpress = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.09), font=FontLabel2(SizeFont+1))
        self.CanvasFrmFond.create_window(int(self.SX * 0.08), int(self.SY * 0.28), anchor=tk.NW,
                                         window=self.EntryExpress)
        self.EntryNom.bind('<KeyRelease>', self.ChangeName)
        self.EntryExpress.bind('<KeyRelease>', self.ChangeName)
        self.EntryExpress.bind('<Return>', self.Appliquer)

        self.BtnAppliquer = BtnAction(self.CanvasFrmFond, int(self.SX * 0.65), int(self.SY * 0.9), RatioX, RatioY,
                                      'Media/FrmTableur/Para/BtnOK/')
        self.BtnAppliquer.CanvasBtn.bind('<ButtonRelease-1>', self.Appliquer)
        self.BtnAnnuler = BtnAction(self.CanvasFrmFond, int(self.SX * 0.8), int(self.SY * 0.9), RatioX, RatioY,
                                    'Media/FrmTableur/Para/BtnAnnul/')
        self.BtnAnnuler.CanvasBtn.bind('<ButtonRelease-1>', self.Annuler)

        if self.MainAppli.TypeAction == 'ModifVar':
            self.ChargeData()

        self.MainAppli.MainAppli.ParaTab = True
        self.lift()
        self.CanvasFrmFond.pack()

    def ChangeName(self, _):
        self.LabelExpress2.Label.config(text=self.EntryNom.get() + ' =')
        self.ChangeNameVar = True

    def ChargeData(self):
        self.LabelTitre.Label.config(text='Modifier la variable')
        if self.MainAppli.VarAModif != self.MainAppli.NCol - 1:
            NomVar = self.MainAppli.TabLabelNCol[self.MainAppli.VarAModif]['text'].split(' (')
            self.NomVar = NomVar[0]
            self.EntryNom.insert(0, NomVar[0])
            if len(NomVar) > 1:
                self.EntryUnit.insert(0, NomVar[1].strip(')'))
        else:
            self.NomVar = ''

        if self.MainAppli.TabExpressCol[self.MainAppli.VarAModif] != '':
            self.LabelExpress2.Label.config(text=self.EntryNom.get() + ' =')
            self.EntryExpress.insert(0, self.MainAppli.TabExpressCol[self.MainAppli.VarAModif])

    def Appliquer(self, _):
        self.BtnAppliquer.CanvasBtn.itemconfig(self.BtnAppliquer.ImgCanvasBtn, image=self.BtnAppliquer.ImgBtn[0])
        if self.EntryNom.get() != '':
            if any(car.isdigit() for car in self.EntryNom.get()) or "(" in self.EntryNom.get() or \
                    " " in self.EntryNom.get():
                self.MainAppli.MainAppli.ShowWarning('Attention',
                                                     "Le nom de la variable ne doit pas contenir de chiffres, "
                                                     "de parenthèses, d'espaces et d'opérateurs mathématiques !")
            else:
                self.NColPrec = self.MainAppli.VarAModif
                if self.NColPrec == self.MainAppli.NCol - 1:
                    self.MainAppli.AjoutCol(1)
                    self.MainAppli.AjoutMatriceCol()
                if self.EntryUnit.get() == '':
                    self.MainAppli.TabLabelNCol[self.NColPrec]['text'] = self.EntryNom.get()
                else:
                    self.MainAppli.TabLabelNCol[self.NColPrec]['text'] = self.EntryNom.get() + ' (' + \
                                                                         self.EntryUnit.get() + ')'
                if self.ChangeNameVar:
                    for i in range(self.MainAppli.NCol):
                        if self.MainAppli.TabExpressCol[i] != '' and self.NomVar != '':
                            self.MainAppli.TabExpressCol[i] = \
                                self.MainAppli.TabExpressCol[i].replace(self.NomVar,
                                                                        self.EntryNom.get())
                self.MainAppli.MAJListVar()
                self.MainAppli.CalculDatas(self.NColPrec)
                self.MainAppli.MAJCalculDatas()
                self.MainAppli.AffichMatriceData()
                self.MainAppli.MainAppli.ModifTab = True
                self.Fermer()
        else:
            self.MainAppli.MainAppli.ShowWarning('Attention', "Veuillez nommer la variable !")

    def Annuler(self, _):
        self.BtnAnnuler.CanvasBtn.itemconfig(self.BtnAnnuler.ImgCanvasBtn, image=self.BtnAnnuler.ImgBtn[0])
        self.Fermer()
        self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.FrmLift2()

    def Fermer(self):
        self.LPDText = self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.LPDText
        self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                           text=self.LPDText)
        self.destroy()
        self.MainAppli.TypeAction = ''
        self.MainAppli.ActionUnSelect()
        self.MainAppli.MainAppli.lift()
        self.MainAppli.MainAppli.ParaTab = False
