from AppliDef import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from scipy.stats import linregress
from scipy.optimize import curve_fit
import numpy as np
from numpy import log, exp, sqrt, cos, sin, tan, pi, abs


def FindMax(l):
    m = 0
    for i in range(len(l)):
        if l[i] > m:
            m = l[i]
    return m


def FindMin(k):
    m = FindMax(k)
    for i in range(len(k)):
        if k[i] < m:
            m = k[i]
    return m


def CalculEcart(Y1, Y2):
    Ecart = 0
    for i in range(len(Y1)):
        Ecart = Ecart + abs(Y2[i] - Y1[i])
    Ecart = Ecart / len(Y1)
    return Ecart


class FrmGraph(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.ModelShow = False
        self.TabShow = False
        self.ZoomActif = False
        self.CurseurActif = False
        self.ModelGraph = None
        self.TableurGraph = None
        self.Xmodel = []
        self.Ymodel = []
        self.Ymodel2 = []
        self.equation = ''
        self.Para1 = 0
        self.Para2 = 0
        self.ListCourbeAxeX = []
        self.ListCourbeAxeY = []
        self.ListCourbePos = []
        self.ListCourbeMinX = []
        self.ListCourbeMinY = []
        self.ListCourbeMaxX = []
        self.ListCourbeMaxY = []
        self.ListCourbeColor = []
        self.ListCourbeSymb = []
        self.ListCourbeStyle = []
        self.ListCourbeTailleSymb = []
        self.NCourbe = 1
        self.NCourbeSelect = 1
        self.ListStyle = ['', '-', '--', ':', '-.']
        self.ListColor = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
        self.ListSymb = ['+', 'o', 'x', '.', '*']
        self.ListX = []
        self.ListY = []
        self.ListLabelAxe = []
        self.ListEquation = []
        self.ListXmodel = []
        self.ListYmodel = []
        self.ListYmodel2 = []
        self.ModelActif = False
        self.NModel = []
        self.ModelOrdre = []
        self.ValModel = []
        self.ListValModel = []
        self.ListEcartModel = []
        self.EcartModel = []
        self.Express = ''
        self.NExpress = 0
        self.OrdrePolyn = 0

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmGraph/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/FrmGraph/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.CacheFrmGraph)

        self.ListBtn = []
        self.BtnPara = BtnAction(self.CanvasFrmFond, int(self.SX * 0.03), int(self.SY * 0.055), self.RatioX,
                                 self.RatioY, 'Media/FrmGraph/BtnPara/')
        self.BtnPara.CanvasBtn.bind('<ButtonRelease-1>', self.AffichPara)
        self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[1])
        self.ListBtn.append(self.BtnPara.CanvasBtn)

        self.BtnModel = BtnAction(self.CanvasFrmFond, int(self.SX * 0.07), int(self.SY * 0.055), self.RatioX,
                                  self.RatioY, 'Media/FrmGraph/BtnModel/')
        self.BtnModel.CanvasBtn.bind('<ButtonRelease-1>', self.AffichModel)
        self.ListBtn.append(self.BtnModel.CanvasBtn)

        self.BtnTableur = BtnAction(self.CanvasFrmFond, int(self.SX * 0.11), int(self.SY * 0.055), self.RatioX,
                                    self.RatioY, 'Media/FrmGraph/BtnTableur/')
        self.BtnTableur.CanvasBtn.bind('<ButtonRelease-1>', self.ActionAffichTableur)
        self.ListBtn.append(self.BtnTableur.CanvasBtn)

        self.BtnZoom = BtnAction(self.CanvasFrmFond, int(self.SX * 0.18), int(self.SY * 0.055), self.RatioX,
                                 self.RatioY, 'Media/FrmGraph/BtnZoom/')
        self.BtnZoom.CanvasBtn.bind('<ButtonRelease-1>', self.ActionZoom)
        self.ListBtn.append(self.BtnZoom.CanvasBtn)

        self.BtnCurseur = BtnAction(self.CanvasFrmFond, int(self.SX * 0.22), int(self.SY * 0.055), self.RatioX,
                                    self.RatioY, 'Media/FrmGraph/BtnCurseur/')
        self.BtnCurseur.CanvasBtn.bind('<ButtonRelease-1>', self.AffichCurseur)
        self.ListBtn.append(self.BtnCurseur.CanvasBtn)

        self.ListAction = ['Modifier les paramètres du graphe', 'Effectuer une modélisation', 'Afficher le tableur',
                           'Effectuer un zoom', 'Afficher les curseurs']

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

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

        self.Graph = Graph_Canvas(self.CanvasFrmFond, int(self.SX * 0.5), int(self.SY * 0.525), int(self.SX * 0.99),
                                  int(self.SY * 0.9), self)
        if self.MainAppli.Tableur.NCol > 2:
            X, Y = self.TracePoints(0, 1)
        else:
            X, Y = self.TracePoints(0, 0)
        self.MaxX = FindMax(X)
        self.MaxY = FindMax(Y)
        self.MaxX = round(self.MaxX * 1.1, 1)
        self.MaxY = round(self.MaxY * 1.1, 1)
        self.MinX = FindMin(X)
        self.MinY = FindMin(Y)
        if self.MinX != 0:
            self.MinX = round(self.MinX * 0.9, 1)
        if self.MinY != 0:
            self.MinY = round(self.MinY * 0.9, 1)

        for i in range(self.MainAppli.Tableur.NCol):
            self.ListLabelAxe.append(self.MainAppli.Tableur.TabLabelNCol[i]['text'])

        self.ListCourbeAxeX.append(0)
        self.ListCourbeAxeY.append(1)
        self.ListCourbePos.append(0)
        self.ListCourbeMinX.append(self.MinX)
        self.ListCourbeMaxX.append(self.MaxX)
        self.ListCourbeMinY.append(self.MinY)
        self.ListCourbeMaxY.append(self.MaxY)
        self.ListCourbeStyle.append(0)
        self.ListCourbeColor.append(0)
        self.ListCourbeSymb.append(0)
        self.ListCourbeTailleSymb.append(8)
        self.ListX.append(X)
        self.ListY.append(Y)
        self.ListEquation.append('')
        self.ListXmodel.append('')
        self.ListYmodel.append('')
        self.ListYmodel2.append('')
        self.NModel.append(0)
        self.ModelOrdre.append(0)
        self.ListValModel.append([])
        self.ListEcartModel.append([])

        self.LabelNameFile = self.CanvasFrmFond.create_text(int(self.SX * 0.01), int(self.SY * 0.016),
                                                            text=self.MainAppli.NameFile, font=FontLabel2(10),
                                                            anchor=tk.W)
        self.LabelAction = self.CanvasFrmFond.create_text(int(self.SX * 0.28), int(self.SY * 0.055),
                                                          text='', font=FontLabel(10), anchor=tk.W)
        self.CanvasFrmFond.addtag_withtag('LabelAction', self.LabelAction)

        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.Graph.AffichCourbes()
        self.MainAppli.GraphAffich = True
        self.CanvasFrmFond.pack()

    def MoveOnBtn(self, _, j):
        self.CanvasFrmFond.itemconfigure('LabelAction', text=self.ListAction[j])

    def MoveOnCanvas(self, _):
        self.CanvasFrmFond.itemconfigure('LabelAction', text='')
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])

    def ActionAffichTableur(self, _):
        if not self.TabShow:
            self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[0])
            self.BtnModel.CanvasBtn.itemconfig(self.BtnModel.ImgCanvasBtn, image=self.BtnModel.ImgBtn[0])
            self.TabShow = True
            self.ModelShow = False
            self.AffichTableur()
        else:
            self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[1])
            self.CacheTab()

    def AffichTableur(self):
        self.TableurGraph = FrmTableurGraph(self.MainAppli.MainAppli.MainAppli.parent, self.RatioX, self.RatioY,
                                            self)

    def AffichPara(self, _):
        if self.ModelShow:
            self.CacheModel()
        else:
            self.CacheTab()
        self.MainAppli.ParaGraph.lift()

    def AffichModel(self, _):
        if not self.ModelShow:
            self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[0])
            self.BtnTableur.CanvasBtn.itemconfig(self.BtnTableur.ImgCanvasBtn, image=self.BtnTableur.ImgBtn[0])
            self.ModelGraph = FrmModelGraph(self.MainAppli.MainAppli.MainAppli.parent, self.RatioX, self.RatioY, self)
            self.ModelShow = True
            self.TabShow = False
        else:
            self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[1])
            self.CacheModel()

    def ActionAffichModel(self):
        self.equation = ''
        self.ValModel = []
        self.EcartModel = []
        if self.ModelGraph.varchoix[0].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, a, rho = self.ModelLin(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
            if self.Xmodel != [] and self.Ymodel != []:
                self.equation = " Y = " + format(a, ".2E") + " * X"
                self.NModel[self.NCourbeSelect - 1] = 1
                self.ValModel.append(a)
                self.EcartModel.append(CalculEcart(self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                                                   self.Ymodel2))
                self.EcartModel.append(rho)

        elif self.ModelGraph.varchoix[1].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, a, b, rho = self.ModelAff(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
            if self.Xmodel != [] and self.Ymodel != []:
                self.equation = (" Y = " + format(a, ".2E") + " * X + " + format(b, ".2E"))
                self.NModel[self.NCourbeSelect - 1] = 2
                self.ValModel.append(a)
                self.ValModel.append(b)
                self.EcartModel.append(CalculEcart(self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                                                   self.Ymodel2))
                self.EcartModel.append(rho)

        elif self.ModelGraph.varchoix[2].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, model = self.ModelPolynome(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                self.OrdrePolyn)
            if self.Xmodel != [] and self.Ymodel != []:
                if int(self.ModelGraph.ListeOrdre.get()) == 1:
                    self.equation = (" Y = " + format(model[0], ".2E") + " * X + " + format(model[1], ".2E"))
                elif int(self.ModelGraph.ListeOrdre.get()) == 2:
                    self.equation = (" Y = " + format(model[0], ".2E") + " * X^2 + " + format(model[1], ".2E") +
                                     " * X + " + format(model[2], ".2E"))
                elif int(self.ModelGraph.ListeOrdre.get()) == 3:
                    self.equation = (" Y = " + format(model[0], ".2E") + " * X^3 + " + format(model[1], ".2E") +
                                     " * X^2 + " + format(model[2], ".2E") + " * X + " + format(model[3], ".2E"))
                self.NModel[self.NCourbeSelect - 1] = 3
                self.ModelOrdre[self.NCourbeSelect - 1] = int(self.ModelGraph.ListeOrdre.get())
                for i in range(len(model)):
                    self.ValModel.append(model[i])
                self.EcartModel.append(CalculEcart(self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                                                   self.Ymodel2))

        elif self.ModelGraph.varchoix[3].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, a, b = self.ModelExp(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
            if self.Xmodel != [] and self.Ymodel != []:
                self.equation = " Y = " + format(a, ".2E") + " * exp(" + format(b, ".2E") + " * X)"
                self.NModel[self.NCourbeSelect - 1] = 4
                self.ValModel.append(a)
                self.ValModel.append(b)
                self.EcartModel.append(CalculEcart(
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.Ymodel2))

        elif self.ModelGraph.varchoix[4].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, a, b = self.ModelLog(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
            if self.Xmodel != [] and self.Ymodel != []:
                self.equation = " Y = " + format(a, ".2E") + " * ln(X) + " + format(b, ".2E")
                self.NModel[self.NCourbeSelect - 1] = 5
                self.ValModel.append(a)
                self.ValModel.append(b)
                self.EcartModel.append(CalculEcart(
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.Ymodel2))

        elif self.ModelGraph.varchoix[5].get() == 1:
            self.Xmodel, self.Ymodel, self.Ymodel2, model = self.ModelPuissance(
                self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
            if self.Xmodel != [] and self.Ymodel != []:
                self.equation = " Y = " + format(model[0], ".2E") + " * X^" + format(model[1], ".2E") + ' + ' \
                                + format(model[2], ".2E")
                self.NModel[self.NCourbeSelect - 1] = 6
                for i in range(len(model)):
                    self.ValModel.append(model[i])
                self.EcartModel.append(CalculEcart(
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.Ymodel2))

        elif self.ModelGraph.varchoix[6].get() == 1:
            if self.ModelGraph.TypeModelPredef == 0:
                self.Xmodel, self.Ymodel, self.Ymodel2, a, b = self.ModelChargeC(
                    self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
                if self.Xmodel != [] and self.Ymodel != []:
                    self.equation = " Y = " + format(a, ".2E") + " * (1 - exp(-X / " + format(b, ".2E") + "))"
                    self.NModel[self.NCourbeSelect - 1] = 7
                    self.ValModel.append(a)
                    self.ValModel.append(b)
                    self.EcartModel.append(CalculEcart(
                        self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                        self.Ymodel2))

            if self.ModelGraph.TypeModelPredef == 1:
                self.Xmodel, self.Ymodel, self.Ymodel2, a, b = self.ModelDechargeC(
                    self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1])
                if self.Xmodel != [] and self.Ymodel != []:
                    self.equation = " Y = " + format(a, ".2E") + " * exp(-X / " + format(b, ".2E") + "))"
                    self.NModel[self.NCourbeSelect - 1] = 8
                    self.ValModel.append(a)
                    self.ValModel.append(b)
                    self.EcartModel.append(CalculEcart(
                        self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                        self.Ymodel2))

            if self.ModelGraph.TypeModelPredef == 2:
                self.Xmodel, self.Ymodel, self.Ymodel2, b = self.ModelCTN(
                    self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1], self.Para1, self.Para2)
                if self.Xmodel != [] and self.Ymodel != []:
                    self.equation = (" Y = " + format(self.Para1, ".2E") + " * exp(" + format(b, ".2E") +
                                     " * (1/X - 1/" + format(self.Para2, ".2E") + ")" + ")")
                    self.NModel[self.NCourbeSelect - 1] = 9
                    self.ValModel.append(b)
                    self.EcartModel.append(CalculEcart(
                        self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                        self.Ymodel2))

            if self.ModelGraph.TypeModelPredef == 3:
                self.Xmodel, self.Ymodel, self.Ymodel2, model = self.ModelPerso(
                    self.MainAppli.Graph.ListX[self.MainAppli.Graph.NCourbeSelect - 1],
                    self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1], self.Express, self.NExpress)
                if self.Xmodel != [] and self.Ymodel != []:
                    self.equation = self.Express
                    self.NModel[self.NCourbeSelect - 1] = 10
                    for i in range(len(model)):
                        self.ValModel.append(model[i])
                    self.EcartModel.append(CalculEcart(
                        self.MainAppli.Graph.ListY[self.MainAppli.Graph.NCourbeSelect - 1],
                        self.Ymodel2))

        if self.equation != '':
            self.ModelActif = True
            self.ListEquation[self.NCourbeSelect - 1] = self.equation
            self.ListXmodel[self.NCourbeSelect - 1] = self.Xmodel
            self.ListYmodel[self.NCourbeSelect - 1] = self.Ymodel
            self.ListYmodel2[self.NCourbeSelect - 1] = self.Ymodel2
            self.ListValModel[self.NCourbeSelect - 1] = self.ValModel
            self.ListEcartModel[self.NCourbeSelect - 1] = self.EcartModel
            self.Graph.AffichModelCourbe(self.Xmodel, self.Ymodel, self.NCourbeSelect - 1)
            self.Graph.AffichLegend()

    def CacheModel(self):
        self.BtnModel.CanvasBtn.itemconfig(self.BtnModel.ImgCanvasBtn, image=self.BtnModel.ImgBtn[0])
        self.ModelGraph.destroy()
        self.ModelShow = False
        self.MainAppli.ParaGraph.lift()
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[1] = False
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[2] = False
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[0] = True
        self.MainAppli.ParaGraph.MenuOnglets.InitOnglets()
        self.MainAppli.ParaGraph.MenuOnglets.ListCanvasMenu[0].itemconfig(
            self.MainAppli.ParaGraph.MenuOnglets.ListImgMenu[0],
            image=self.MainAppli.ParaGraph.MenuOnglets.ListMenu[0][2])

    def CacheTab(self):
        self.BtnTableur.CanvasBtn.itemconfig(self.BtnTableur.ImgCanvasBtn, image=self.BtnTableur.ImgBtn[0])
        self.TableurGraph.destroy()
        self.TabShow = False
        self.MainAppli.ParaGraph.lift()
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[2] = False
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[1] = False
        self.MainAppli.ParaGraph.MenuOnglets.MenuSelected[0] = True
        self.MainAppli.ParaGraph.MenuOnglets.InitOnglets()
        self.MainAppli.ParaGraph.MenuOnglets.ListCanvasMenu[0].itemconfig(
            self.MainAppli.ParaGraph.MenuOnglets.ListImgMenu[0],
            image=self.MainAppli.ParaGraph.MenuOnglets.ListMenu[0][2])

    def ModelLin(self, x, y):
        def fonction(t, a):
            return a * t

        Xmod = []
        Ymod = []
        Ymod2 = []
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0]))
            Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                             self.ListCourbeMaxX[self.NCourbeSelect - 1],
                             (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                              self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
            Ymod = fonction(Xmod, params[0])
        x2 = list(x)
        y2 = list(y)
        x2.append(0)
        y2.append(0)
        modele = linregress(x2, y2)
        return Xmod, Ymod, Ymod2, params[0], modele[2]

    def ModelAff(self, x, y):
        modele = linregress(x, y)
        Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                         self.ListCourbeMaxX[self.NCourbeSelect - 1],
                         (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                          self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
        Ymod = modele[0] * Xmod + modele[1]
        Ymod2 = []
        for i in range(len(x)):
            Ymod2.append(modele[0] * x[i] + modele[1])
        return Xmod, Ymod, Ymod2, modele[0], modele[1], modele[2]

    def ModelLog(self, x, y):
        def fonction(t, a, b):
            return a * np.log(t) + b

        Xmod = []
        Ymod = []
        Ymod2 = []
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0], params[1]))
            Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                             self.ListCourbeMaxX[self.NCourbeSelect - 1],
                             (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                              self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
            Ymod = fonction(Xmod, params[0], params[1])
        return Xmod, Ymod, Ymod2, params[0], params[1]

    def ModelExp(self, x, y):
        def fonction(t, a, b):
            return a * np.exp(b * t)

        Xmod = []
        Ymod = []
        Ymod2 = []
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0], params[1]))
            Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                             self.ListCourbeMaxX[self.NCourbeSelect - 1],
                             (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                              self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
            Ymod = fonction(Xmod, params[0], params[1])
        return Xmod, Ymod, Ymod2, params[0], params[1]

    def ModelPuissance(self, x, y):
        def fonction(t, a, b, c):
            return a * t ** b + c

        Xmod = []
        Ymod = []
        Ymod2 = []
        params = []
        try:
            params, covar = curve_fit(fonction, x, y)
            perr = np.sqrt(np.diag(covar))
            if str(perr[0]) == 'inf':
                tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
                self.lift()
                self.ModelGraph.lift()
            else:
                for i in range(len(x)):
                    Ymod2.append(fonction(x[i], params[0], params[1], params[2]))
                Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                                 self.ListCourbeMaxX[self.NCourbeSelect - 1],
                                 (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                                  self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
                Ymod = fonction(Xmod, params[0], params[1], params[2])
        except:
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        finally:
            return Xmod, Ymod, Ymod2, params

    def ModelPerso(self, x, y, Express, n):
        def fonction(X, a):
            ListVar = vars()
            ListVar['x'] = X
            ListVar['a'] = a
            return eval(Express)

        def fonction2(X, a, b):
            ListVar = vars()
            ListVar['x'] = X
            ListVar['a'] = a
            ListVar['b'] = b
            return eval(Express)

        def fonction3(X, a, b, c):
            ListVar = vars()
            ListVar['x'] = X
            ListVar['a'] = a
            ListVar['b'] = b
            ListVar['c'] = c
            return eval(Express)

        def fonction4(X, a, b, c, d):
            ListVar = vars()
            ListVar['x'] = X
            ListVar['a'] = a
            ListVar['b'] = b
            ListVar['c'] = c
            ListVar['d'] = d
            return eval(Express)

        Xmod = []
        Ymod = []
        Ymod2 = []
        params = []
        try:
            if n == 1:
                params, covar = curve_fit(fonction, x, y)
            elif n == 2:
                params, covar = curve_fit(fonction2, x, y)
            elif n == 3:
                params, covar = curve_fit(fonction3, x, y)
            else:
                params, covar = curve_fit(fonction4, x, y)
            perr = np.sqrt(np.diag(covar))
            if str(perr[0]) == 'inf':
                tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
                self.lift()
                self.ModelGraph.lift()
            else:
                for i in range(len(x)):
                    if n == 1:
                        Ymod2.append(fonction(x[i], params[0]))
                    elif n == 2:
                        Ymod2.append(fonction2(x[i], params[0], params[1]))
                    elif n == 3:
                        Ymod2.append(fonction3(x[i], params[0], params[1], params[2]))
                    else:
                        Ymod2.append(fonction4(x[i], params[0], params[1], params[2], params[3]))
                Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                                 self.ListCourbeMaxX[self.NCourbeSelect - 1],
                                 (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                                  self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
                if n == 1:
                    Ymod = fonction(Xmod, params[0])
                elif n == 2:
                    Ymod = fonction2(Xmod, params[0], params[1])
                elif n == 3:
                    Ymod = fonction3(Xmod, params[0], params[1], params[2])
                else:
                    Ymod = fonction4(Xmod, params[0], params[1], params[2], params[3])
        except:
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        finally:
            return Xmod, Ymod, Ymod2, params

    def ModelPolynome(self, x, y, deg):
        def fonction(X, a, b):
            return a * X + b

        def fonction2(X, a, b, c):
            return a * X ** 2 + b * X + c

        def fonction3(X, a, b, c, d):
            return a * X ** 3 + b * X ** 2 + c * X + d

        Xmod = []
        Ymod = []
        Ymod2 = []
        model = []
        covar = []
        try:
            if deg == 1:
                model, covar = curve_fit(fonction, x, y)
            elif deg == 2:
                model, covar = curve_fit(fonction2, x, y)
            elif deg == 3:
                model, covar = curve_fit(fonction3, x, y)
            perr = np.sqrt(np.diag(covar))
            if str(perr[0]) == 'inf':
                tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
                self.lift()
                self.ModelGraph.lift()
            else:
                Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                                 self.ListCourbeMaxX[self.NCourbeSelect - 1],
                                 (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                                  self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
                if deg == 1:
                    Ymod = fonction(Xmod, model[0], model[1])
                    for i in range(len(x)):
                        Ymod2.append(fonction(x[i], model[0], model[1]))
                elif deg == 2:
                    Ymod = fonction2(Xmod, model[0], model[1], model[2])
                    for i in range(len(x)):
                        Ymod2.append(fonction2(x[i], model[0], model[1], model[2]))
                elif deg == 3:
                    Ymod = fonction3(Xmod, model[0], model[1], model[2], model[3])
                    for i in range(len(x)):
                        Ymod2.append(fonction3(x[i], model[0], model[1], model[2], model[3]))
        except:
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        finally:
            return Xmod, Ymod, Ymod2, model

    def ModelChargeC(self, x, y):
        def fonction(t, E, tau):
            return E * (1 - np.exp(-t / tau))

        Xmod = []
        Ymod = []
        Ymod2 = []
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0], params[1]))
            Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                             self.ListCourbeMaxX[self.NCourbeSelect - 1],
                             (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                              self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
            Ymod = fonction(Xmod, params[0], params[1])
        return Xmod, Ymod, Ymod2, params[0], params[1]

    def ModelDechargeC(self, x, y):
        def fonction(t, E, tau):
            return E * np.exp(-t / tau)

        Xmod = []
        Ymod = []
        Ymod2 = []
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0], params[1]))
            Xmod = np.arange(self.ListCourbeMinX[self.NCourbeSelect - 1],
                             self.ListCourbeMaxX[self.NCourbeSelect - 1],
                             (self.ListCourbeMaxX[self.NCourbeSelect - 1] -
                              self.ListCourbeMinX[self.NCourbeSelect - 1]) / 1000)
            Ymod = fonction(Xmod, params[0], params[1])
        return Xmod, Ymod, Ymod2, params[0], params[1]

    def ModelCTN(self, x, y, Ro, To):

        def fonction(T, b):
            return Ro * np.exp(b * ((1 / T) - (1 / To)))

        Xmod = []
        Ymod = []
        Ymod2 = []
        Min = 0
        params, covar = curve_fit(fonction, x, y)
        perr = np.sqrt(np.diag(covar))
        if str(perr[0]) == 'inf':
            tkMB.showwarning('Attention', "Le model choisi n'est pas adapté !")
            self.lift()
            self.ModelGraph.lift()
        else:
            for i in range(len(x)):
                Ymod2.append(fonction(x[i], params[0]))
            for i in range(int(self.ListCourbeMaxX[self.NCourbeSelect - 1]),
                           int(self.ListCourbeMinX[self.NCourbeSelect - 1]), -1):
                if fonction(i, params[0]) > self.ListCourbeMaxY[self.NCourbeSelect - 1]:
                    Min = i
                    break
            Xmod = np.arange(Min, self.ListCourbeMaxX[self.NCourbeSelect - 1], 1)
            Ymod = fonction(Xmod, params[0])
        return Xmod, Ymod, Ymod2, params[0]

    def TracePoints(self, NColX, NColY):
        X = []
        Y = []
        try:
            for i in range(self.MainAppli.Tableur.Npoint):
                if self.MainAppli.Tableur.TabLabels[i][NColY]['text'] != '':
                    Y.append(float(self.MainAppli.Tableur.TabLabels[i][NColY]['text'].replace(',', '.')))
                if self.MainAppli.Tableur.TabLabels[i][NColX]['text'] != '':
                    X.append(float(self.MainAppli.Tableur.TabLabels[i][NColX]['text'].replace(',', '.')))
            return X, Y
        except:
            pass

    def ActionZoom(self, _):
        if not self.ZoomActif:
            self.ZoomActif = True
            ChangeCursor(self.MainAppli.Graph.Graph.CanvasGraph)
            self.MainAppli.Graph.Graph.ZoneRecadrage = self.MainAppli.Graph.Graph.CanvasGraph.create_rectangle(
                0, 0, 0, 0)
        else:
            self.BtnZoom.CanvasBtn.itemconfig(self.BtnZoom.ImgCanvasBtn, image=self.BtnZoom.ImgBtn[0])
            self.ZoomActif = False
            self.MainAppli.Graph.Graph.CanvasGraph.delete(self.MainAppli.Graph.Graph.ZoneRecadrage)
            self.MainAppli.Graph.Graph.AffichCourbes()

    def AffichCurseur(self, _):
        if not self.CurseurActif:
            self.CurseurActif = True
            ChangeCursor(self.MainAppli.Graph.Graph.CanvasGraph)
        else:
            if self.TabShow:
                self.TableurGraph.UnSelectLine()
            self.BtnCurseur.CanvasBtn.itemconfig(self.BtnCurseur.ImgCanvasBtn, image=self.BtnCurseur.ImgBtn[0])
            self.CurseurActif = False
            self.Graph.CurseurHG.set_data([], [])
            self.Graph.CurseurHD.set_data([], [])
            self.Graph.CurseurVG.set_data([], [])
            self.Graph.CurseurVD.set_data([], [])
            self.Graph.graphfig.draw()

    def CacheFrmGraph(self, _):
        self.MainAppli.ParaGraph.destroy()
        self.destroy()
        self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
        self.MainAppli.lift()
        self.MainAppli.GraphAffich = False
        if self.MainAppli.MainAppli.MainAppli.MainAppli.AffichTabSM:
            self.MainAppli.MainAppli.MainAppli.MainAppli.LPDText = "Données envoyées par l'Arduino UNO"
            self.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
                'LegendePanneauD', text=self.MainAppli.MainAppli.MainAppli.MainAppli.LPDText)
            self.MainAppli.ArdData.lift()
        else:
            self.MainAppli.MainAppli.MainAppli.MainAppli.LPDText = 'ArdPyLog - Gestionnaire de sketchs pour Arduino UNO'
            self.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure(
                'LegendePanneauD', text=self.MainAppli.MainAppli.MainAppli.MainAppli.LPDText)


def FindMinMaxXY(Min, NbrMin, Max, NbrMax):
    if Min is None:
        Min = NbrMin
    else:
        if NbrMin < Min:
            Min = NbrMin

    if Max is None:
        Max = NbrMax
    else:
        if NbrMax > Max:
            Max = NbrMax

    return Min, Max


class Graph_Canvas(tk.Canvas):
    def __init__(self, conteneur, X, Y, W, H, Appli):
        tk.Canvas.__init__(self, conteneur, width=W, height=H, highlightthickness=0, bd=0)
        conteneur.create_window(X, Y, anchor=tk.CENTER, window=self)
        self.MainAppli = Appli
        self.ListCourbesD = []
        self.ListCourbesG = []
        self.ListModelsG = []
        self.ListModelsD = []
        self.ListModelsLegend = []
        self.ListEquation = []
        self.LegCourbeMultiple = None
        self.LegCourbeModel = None
        self.ListCourbeLegend = []
        self.ListLegend = []
        self.LegendActif = False
        self.ZoneRecadrage = None
        self.X1Mouse = 0
        self.Y1Mouse = 0
        self.X2Mouse = 0
        self.Y2Mouse = 0
        self.XZT = 0
        self.YZT = 0
        self.X0 = int(W * 0.046)
        self.Y0 = int(H * 0.022)
        self.Y1 = int(H * 0.948)
        self.X1 = int(W * 0.957)
        self.MinXG, self.MinYG, self.MaxXG, self.MaxYG = None, None, None, None
        self.MinXD, self.MinYD, self.MaxXD, self.MaxYD = None, None, None, None
        self.CW = W
        self.CH = H
        self.Xcur = 0
        self.XcurTab = 0
        self.Ycur = 0

        mydpi = 96
        self.fig = Figure(figsize=(W / mydpi, H / mydpi), dpi=mydpi, facecolor='white')
        self.Graph = self.fig.add_subplot(111)
        self.Graph.patch.set_facecolor('white')
        self.Graph.tick_params(axis="y", labelrotation=90)
        self.Graph.grid(which='major', alpha=0.5, linewidth=0.6, color="#ababab")

        self.graphfig = FigureCanvasTkAgg(self.fig, master=self)
        self.CanvasGraph = self.graphfig.get_tk_widget()

        self.CanvasGraph.bind("<Button-1>", self.ClicOnCanvas)
        self.CanvasGraph.bind("<B1 - Motion>", self.DessineZoneRecadrage)
        self.CanvasGraph.bind("<Motion>", self.AffichCurseur)
        self.MenuClicDroit = tk.Menu(self.CanvasGraph, tearoff=0)
        self.MenuClicDroit.add_command(label="Valider", command=self.ValidRecadrage)
        self.MenuClicDroit.add_separator()
        self.MenuClicDroit.add_command(label="Annuler", command=self.AnnulRecadrage)
        self.CanvasGraph.bind("<Button-3>", self.AffichMenuClicDroit)

        self.fig.tight_layout(rect=[0.01, 0.01, 0.98, 1])

        self.Graph2 = self.Graph.twinx()
        self.Graph2.tick_params(axis="y", labelrotation=90)

        self.CurseurHG, = self.Graph.plot([], [], color='orange')
        self.CurseurHD, = self.Graph2.plot([], [], color='orange')
        self.CurseurVG, = self.Graph.plot([], [], color='orange')
        self.CurseurVD, = self.Graph2.plot([], [], color='orange')

        self.TextX = self.CanvasGraph.create_text(0, 0, text='')
        self.TextY = self.CanvasGraph.create_text(0, 0, text='')

        self.AjoutCourbe()
        self.CanvasGraph.pack()

    def AffichCourbes(self):
        self.EffaceCourbes()
        self.Graph.set_xlabel(self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeX[0]], weight='bold')
        LabelYG = ''
        LabelYD = ''
        if not self.MainAppli.ZoomActif:
            self.MinXG, self.MinYG, self.MaxXG, self.MaxYG = None, None, None, None
            self.MinXD, self.MinYD, self.MaxXD, self.MaxYD = None, None, None, None
        self.ListCourbeLegend = []
        self.ListLegend = []
        for i in range(self.MainAppli.NCourbe):
            if self.MainAppli.ListCourbePos[i] == 0:
                self.Graph.tick_params(axis='y', which='both', left=True, right=False, labelleft=True, labelright=False)

                self.ListCourbesG[i].set_color(self.MainAppli.ListColor[self.MainAppli.ListCourbeColor[i]])
                self.ListCourbesG[i].set_linestyle(self.MainAppli.ListStyle[self.MainAppli.ListCourbeStyle[i]])
                self.ListCourbesG[i].set_marker(self.MainAppli.ListSymb[self.MainAppli.ListCourbeSymb[i]])
                self.ListCourbesG[i].set_markersize(self.MainAppli.ListCourbeTailleSymb[i])

                if LabelYG != '':
                    LabelYG = LabelYG + ' ; ' + self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]]
                else:
                    LabelYG = self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]]

                if not self.MainAppli.ZoomActif:
                    self.MinXG, self.MaxXG = FindMinMaxXY(self.MinXG, self.MainAppli.ListCourbeMinX[i], self.MaxXG,
                                                          self.MainAppli.ListCourbeMaxX[i])
                    self.MinYG, self.MaxYG = FindMinMaxXY(self.MinYG, self.MainAppli.ListCourbeMinY[i], self.MaxYG,
                                                          self.MainAppli.ListCourbeMaxY[i])

                self.Graph.set_ylabel(LabelYG, weight='bold')
                self.Graph.set_xlim(self.MinXG, self.MaxXG)
                self.Graph.set_ylim(self.MinYG, self.MaxYG)

                self.ListCourbesG[i].set_data(self.MainAppli.ListX[i], self.MainAppli.ListY[i])
                self.ListCourbeLegend.append(self.ListCourbesG[i])
                self.ListLegend.append('Courbe ' + str(i + 1) + ' : ' +
                                       self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]])

                if self.MainAppli.ListEquation[i] != '':
                    self.AffichModelCourbe(self.MainAppli.ListXmodel[i], self.MainAppli.ListYmodel[i], i)
            else:
                self.Graph2.tick_params(axis='y', which='both', left=False, right=True, labelleft=False,
                                        labelright=True)

                self.ListCourbesD[i].set_color(self.MainAppli.ListColor[self.MainAppli.ListCourbeColor[i]])
                self.ListCourbesD[i].set_linestyle(self.MainAppli.ListStyle[self.MainAppli.ListCourbeStyle[i]])
                self.ListCourbesD[i].set_marker(self.MainAppli.ListSymb[self.MainAppli.ListCourbeSymb[i]])
                self.ListCourbesD[i].set_markersize(self.MainAppli.ListCourbeTailleSymb[i])

                if LabelYD != '':
                    LabelYD = LabelYD + ' ; ' + self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]]
                else:
                    LabelYD = self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]]

                if not self.MainAppli.ZoomActif:
                    self.MinXD, self.MaxXD = FindMinMaxXY(self.MinXD, self.MainAppli.ListCourbeMinX[i], self.MaxXD,
                                                          self.MainAppli.ListCourbeMaxX[i])
                    self.MinYD, self.MaxYD = FindMinMaxXY(self.MinYD, self.MainAppli.ListCourbeMinY[i], self.MaxYD,
                                                          self.MainAppli.ListCourbeMaxY[i])

                self.Graph2.set_ylabel(LabelYD, weight='bold')
                self.Graph2.set_xlim(self.MinXD, self.MaxXD)
                self.Graph2.set_ylim(self.MinYD, self.MaxYD)

                self.ListCourbesD[i].set_data(self.MainAppli.ListX[i], self.MainAppli.ListY[i])
                self.ListCourbeLegend.append(self.ListCourbesD[i])
                self.ListLegend.append('Courbe ' + str(i + 1) + ' : ' +
                                       self.MainAppli.ListLabelAxe[self.MainAppli.ListCourbeAxeY[i]])
                if self.MainAppli.ListEquation[i] != '':
                    self.AffichModelCourbe(self.MainAppli.ListXmodel[i], self.MainAppli.ListYmodel[i], i)
        if self.MainAppli.NCourbe > 1 or self.MainAppli.ModelActif:
            self.AffichLegend()
        else:
            self.graphfig.draw()

    def AffichModelCourbe(self, X, Y, Ncourbe):
        if self.MainAppli.ListCourbePos[Ncourbe] == 0:
            self.ListModelsG[Ncourbe].set_color(self.MainAppli.ListColor[self.MainAppli.ListCourbeColor[Ncourbe]])
            self.ListModelsG[Ncourbe].set_data(X, Y)
            self.ListModelsLegend[Ncourbe] = self.ListModelsG[Ncourbe]
        else:
            self.ListModelsD[Ncourbe].set_color(self.MainAppli.ListColor[self.MainAppli.ListCourbeColor[Ncourbe]])
            self.ListModelsD[Ncourbe].set_data(X, Y)
            self.ListModelsLegend[Ncourbe] = self.ListModelsD[Ncourbe]
        self.ListEquation[Ncourbe] = self.MainAppli.ListEquation[Ncourbe]
        self.graphfig.draw()

    def AffichLegend(self):
        if self.LegendActif:
            self.EffaceLegends()
        if self.MainAppli.ModelActif and self.MainAppli.NCourbe > 1:
            self.LegCourbeMultiple = self.Graph2.legend(self.ListCourbeLegend, self.ListLegend, loc='upper right')
            self.Graph.legend(self.ListModelsLegend, self.ListEquation, loc='upper left')
            self.LegendActif = True
        elif self.MainAppli.NCourbe > 1:
            self.Graph.legend(self.ListCourbeLegend, self.ListLegend, loc='upper right')
            self.LegendActif = True
        elif self.MainAppli.ModelActif:
            self.Graph.legend(self.ListModelsLegend, self.ListEquation, loc='upper left')
            self.LegendActif = True
        else:
            self.LegendActif = False
        self.graphfig.draw()

    def AjoutCourbe(self):
        PointCourbe, = self.Graph.plot([], [])
        PointCourbe2, = self.Graph2.plot([], [])
        ModelCourbe, = self.Graph.plot([], [], color='white')
        ModelCourbe2, = self.Graph2.plot([], [], color='white')
        self.ListModelsG.append(ModelCourbe)
        self.ListModelsD.append(ModelCourbe2)
        self.ListCourbesG.append(PointCourbe)
        self.ListCourbesD.append(PointCourbe2)
        self.ListModelsLegend.append(ModelCourbe)
        self.ListEquation.append('')

    def EffaceCourbes(self):
        self.Graph.tick_params(axis='y', which='both', left=False, right=False, labelleft=False, labelright=False)
        self.Graph2.tick_params(axis='y', which='both', left=False, right=False, labelleft=False, labelright=False)
        self.Graph.set_xlabel('')
        self.Graph.set_ylabel('')
        self.Graph2.set_xlabel('')
        self.Graph2.set_ylabel('')
        for i in range(self.MainAppli.NCourbe):
            self.ListCourbesG[i].set_data([], [])
            self.ListCourbesD[i].set_data([], [])
            self.ListModelsG[i].set_data([], [])
            self.ListModelsD[i].set_data([], [])
        if self.MainAppli.CurseurActif:
            self.CurseurHG.set_data([], [])
            self.CurseurHD.set_data([], [])
            self.CurseurVG.set_data([], [])
            self.CurseurVD.set_data([], [])
        self.graphfig.draw()

    def EffaceLegends(self):
        self.Graph.legend_.remove()
        if self.LegCourbeMultiple is not None and self.MainAppli.ModelActif:
            self.LegCourbeMultiple.remove()
        self.LegendActif = False
        self.graphfig.draw()

    def ClicOnCanvas(self, event):
        if self.MainAppli.ZoomActif and not self.MainAppli.CurseurActif:
            X = event.x
            Y = event.y
            self.CanvasGraph.delete(self.ZoneRecadrage)
            self.ZoneRecadrage = self.CanvasGraph.create_rectangle(0, 0, 0, 0)
            if self.X0 < X < self.X1 and self.Y0 < Y < self.Y1:
                self.X1Mouse = X
                self.Y1Mouse = Y
            else:
                self.X1Mouse = self.X0
                self.Y1Mouse = self.Y0
        elif self.MainAppli.CurseurActif:
            if not self.MainAppli.TabShow:
                if not self.MainAppli.ModelShow:
                    self.MainAppli.MainAppli.ParaGraph.ClicOnMenu(event, 2)
                else:
                    self.MainAppli.ModelGraph.ClicOnMenu(event, 2)
                self.MainAppli.TabShow = True
            self.MainAppli.TableurGraph.SelectLine(self.MainAppli.NCourbeSelect - 1, self.XcurTab)

    def DessineZoneRecadrage(self, event):
        if self.MainAppli.ZoomActif:
            X = event.x
            Y = event.y
            if self.X0 < X < self.X1 and self.Y0 < Y < self.Y1 and self.X1Mouse < X and self.Y1Mouse < Y:
                self.CanvasGraph.delete(self.ZoneRecadrage)
                self.X2Mouse = X
                self.Y2Mouse = Y
                self.ZoneRecadrage = self.CanvasGraph.create_rectangle(self.X1Mouse, self.Y1Mouse, self.X2Mouse,
                                                                       self.Y2Mouse, width=1)

    def AffichMenuClicDroit(self, event):
        if self.MainAppli.ZoomActif:
            self.XZT = event.x
            self.YZT = event.y
            if self.X2Mouse > self.X1Mouse:
                if self.Y2Mouse > self.Y1Mouse:
                    if self.X1Mouse < self.XZT < self.X2Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
                else:
                    if self.X1Mouse < self.XZT < self.X2Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
            else:
                if self.Y2Mouse > self.Y1Mouse:
                    if self.X2Mouse < self.XZT < self.X1Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)
                else:
                    if self.X2Mouse < self.XZT < self.X1Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                        self.MenuClicDroit.post(event.x_root, event.y_root)

    def AnnulRecadrage(self):
        if self.X2Mouse > self.X1Mouse:
            if self.Y2Mouse > self.Y1Mouse:
                if self.X1Mouse < self.XZT < self.X2Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                    self.CanvasGraph.delete(self.ZoneRecadrage)
            else:
                if self.X1Mouse < self.XZT < self.X2Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                    self.CanvasGraph.delete(self.ZoneRecadrage)
        else:
            if self.Y2Mouse > self.Y1Mouse:
                if self.X2Mouse < self.XZT < self.X1Mouse and self.Y1Mouse < self.YZT < self.Y2Mouse:
                    self.CanvasGraph.delete(self.ZoneRecadrage)
            else:
                if self.X2Mouse < self.XZT < self.X1Mouse and self.Y2Mouse < self.YZT < self.Y1Mouse:
                    self.CanvasGraph.delete(self.ZoneRecadrage)
        self.X1Mouse, self.X2Mouse, self.Y1Mouse, self.Y2Mouse = 0, 0, 0, 0
        self.MainAppli.ZoomActif = False
        ChangeCursor3(self.CanvasGraph)
        self.MainAppli.BtnZoom.CanvasBtn.itemconfig(self.MainAppli.BtnZoom.ImgCanvasBtn,
                                                    image=self.MainAppli.BtnZoom.ImgBtn[0])

    def ValidRecadrage(self):
        self.CanvasGraph.delete(self.ZoneRecadrage)
        X0G, X0D, X1G, X1D = self.MinXG, self.MinXD, self.MaxXG, self.MaxXD
        Y0G, Y0D, Y1G, Y1D = self.MinYG, self.MinYD, self.MaxYG, self.MaxYD
        if self.MinXG is not None:
            self.MinXG = X0G + abs(X1G - X0G) * (self.X1Mouse - self.X0) / abs(self.X1 - self.X0)
        if self.MinXD is not None:
            self.MinXD = X0D + abs(X1D - X0D) * (self.X1Mouse - self.X0) / abs(self.X1 - self.X0)
        if self.MaxXG is not None:
            self.MaxXG = X0G + abs(X1G - X0G) * (self.X2Mouse - self.X0) / abs(self.X1 - self.X0)
        if self.MaxXD is not None:
            self.MaxXD = X0D + abs(X1D - X0D) * (self.X2Mouse - self.X0) / abs(self.X1 - self.X0)
        if self.MinYG is not None:
            self.MinYG = Y1G - abs(Y1G - Y0G) * self.Y2Mouse / abs(self.Y1 - self.Y0)
        if self.MinYD is not None:
            self.MinYD = Y1D - abs(Y1D - Y0D) * self.Y2Mouse / abs(self.Y1 - self.Y0)
        if self.MaxYG is not None:
            self.MaxYG = Y1G - abs(Y1G - Y0G) * self.Y1Mouse / abs(self.Y1 - self.Y0)
        if self.MaxYD is not None:
            self.MaxYD = Y1D - abs(Y1D - Y0D) * self.Y1Mouse / abs(self.Y1 - self.Y0)
        self.AffichCourbes()

    def AffichCurseur(self, event):
        self.MainAppli.CanvasFrmFond.itemconfigure('LabelAction', text='')
        if self.MainAppli.CurseurActif:
            X = event.x
            Y = event.y
            self.CanvasGraph.delete(self.TextX)
            self.CanvasGraph.delete(self.TextY)
            if self.X0 < X < self.X1 and self.Y0 < Y < self.Y1:
                self.Xcur = self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1] + \
                            abs(self.MainAppli.ListCourbeMaxX[self.MainAppli.NCourbeSelect - 1] -
                                self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1]) * (
                                    X - self.X0) / abs(self.X1 - self.X0)
                self.Ycur = 0
                FoundPoint = False
                if self.MainAppli.ListEquation[self.MainAppli.NCourbeSelect - 1] != '':
                    for i in range(len(self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1):
                        if (self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i] < self.Xcur <
                                self.MainAppli.ListX[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] or self.MainAppli.ListX[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] < self.Xcur <
                                self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i]):
                            self.XcurTab = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i]
                            FoundPoint = True
                            break
                    if not FoundPoint:
                        if self.Xcur > self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][len(
                                self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1]:
                            self.XcurTab = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][
                                len(self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1]
                        else:
                            self.XcurTab = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][0]
                    for i in range(len(self.MainAppli.ListXmodel[self.MainAppli.NCourbeSelect - 1]) - 1):
                        if (self.MainAppli.ListXmodel[self.MainAppli.NCourbeSelect - 1][i] < self.Xcur <
                                self.MainAppli.ListXmodel[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] or self.MainAppli.ListXmodel[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] < self.Xcur <
                                self.MainAppli.ListXmodel[self.MainAppli.NCourbeSelect - 1][i]):
                            self.Xcur = self.MainAppli.ListXmodel[self.MainAppli.NCourbeSelect - 1][i]
                            self.Ycur = self.MainAppli.ListYmodel[self.MainAppli.NCourbeSelect - 1][i]
                            break
                else:
                    FoundPoint = False
                    for i in range(len(self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1):
                        if (self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i] < self.Xcur <
                                self.MainAppli.ListX[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] or self.MainAppli.ListX[
                                    self.MainAppli.NCourbeSelect - 1][i + 1] < self.Xcur <
                                self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i]):
                            self.Xcur = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][i]
                            self.Ycur = self.MainAppli.ListY[self.MainAppli.NCourbeSelect - 1][i]
                            FoundPoint = True
                            break
                    if not FoundPoint:
                        if self.Xcur > self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][len(
                                self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1]:
                            self.Xcur = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][
                                len(self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1]) - 1]
                            self.Ycur = self.MainAppli.ListY[self.MainAppli.NCourbeSelect - 1][
                                len(self.MainAppli.ListY[self.MainAppli.NCourbeSelect - 1]) - 1]
                        else:
                            self.Xcur = self.MainAppli.ListX[self.MainAppli.NCourbeSelect - 1][0]
                            self.Ycur = self.MainAppli.ListY[self.MainAppli.NCourbeSelect - 1][0]
                    self.XcurTab = self.Xcur

                self.ActionAffichCurseur()

    def ActionAffichCurseur(self):
        XcurText = int(self.X0 + (self.Xcur - self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1]) *
                       abs(self.X1 - self.X0) / abs(
            self.MainAppli.ListCourbeMaxX[self.MainAppli.NCourbeSelect - 1] -
            self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1]) + self.CW * 0.015)
        self.TextX = self.CanvasGraph.create_text(XcurText, int(self.Y1 * 0.99), text=str(round(self.Xcur, 2)))

        YcurText = int(self.Y0 + (self.MainAppli.ListCourbeMaxY[self.MainAppli.NCourbeSelect - 1] - self.Ycur) *
                       abs(self.Y1 - self.Y0) / abs(
            self.MainAppli.ListCourbeMaxY[self.MainAppli.NCourbeSelect - 1] -
            self.MainAppli.ListCourbeMinY[self.MainAppli.NCourbeSelect - 1]) - self.CH * 0.012)
        self.TextY = self.CanvasGraph.create_text(int(self.X0 * 1.25), YcurText,
                                                  text=str(round(self.Ycur, 2)))

        if self.MainAppli.ListCourbePos[self.MainAppli.NCourbeSelect - 1] == 0:
            self.CurseurVG.set_data([self.Xcur, self.Xcur],
                                    [self.MainAppli.ListCourbeMinY[self.MainAppli.NCourbeSelect - 1],
                                     self.MainAppli.ListCourbeMaxY[self.MainAppli.NCourbeSelect - 1]])
            self.CurseurHG.set_data([self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1],
                                     self.MainAppli.ListCourbeMaxX[self.MainAppli.NCourbeSelect - 1]],
                                    [self.Ycur, self.Ycur])
        else:
            self.CurseurVD.set_data([self.Xcur, self.Xcur],
                                    [self.MainAppli.ListCourbeMinY[self.MainAppli.NCourbeSelect - 1],
                                     self.MainAppli.ListCourbeMaxY[self.MainAppli.NCourbeSelect - 1]])
            self.CurseurHD.set_data([self.MainAppli.ListCourbeMinX[self.MainAppli.NCourbeSelect - 1],
                                     self.MainAppli.ListCourbeMaxX[self.MainAppli.NCourbeSelect - 1]],
                                    [self.Ycur, self.Ycur])
        self.graphfig.draw()


def DeterminIndex(L):
    N = 0
    i = 1
    while N == 0:
        if i in L:
            i = i + 1
        else:
            N = i
    return N


class FrmParaGraph(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.IndexColX = -1
        self.IndexColY = -1
        self.NCourbeSelect = 1
        self.ModifAxe = 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.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                 text="Graphes - Paramètres")
        self.LabelTitre = LabelInCanvas(self.CanvasFrmFond, 'Représentation graphique Y = F(X)', '#F7F7F7',
                                        FontLabelTitre(10), self.SX * 0.05, self.SY * 0.03)

        self.ImgGraph, wsize, hsize, self.CanvasGraph, self.ImgCanvasGraph = CanInWindow(
            'Media/FrmGraph/Paragraph/', self.RatioX, self.RatioY, self.CanvasFrmFond,
            int(self.SX * 0.65), int(self.SY * 0.18), 0)

        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.MainAppli.MainAppli.Nconfig, 'G1'))
        self.SizeFont = SizeFont
        self.LabelAxeX = LabelInCanvas(self.CanvasFrmFond, 'Axe X', '#F7F7F7', FontLabel(SizeFont), self.SX * 0.6,
                                       self.SY * 0.28)
        self.LabelAxeY = LabelInCanvas(self.CanvasFrmFond, 'Axe Y', '#F7F7F7', FontLabel(SizeFont), self.SX * 0.15,
                                       self.SY * 0.13)

        self.ListCourbe = []
        self.ListCourbe.append('Courbe 1')
        self.ListeCourbe = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.022), values=self.ListCourbe)
        self.ListeCourbe.config(font=FontLabel(SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.865), int(self.SY * 0.03), anchor=tk.CENTER,
                                         window=self.ListeCourbe)
        self.ListeCourbe.current(0)
        self.ListeCourbe.bind("<<ComboboxSelected>>", self.ChargePara)

        self.BtnAjout = BtnAction(self.CanvasFrmFond, int(self.SX * 0.75), int(self.SY * 0.03), self.RatioX,
                                  self.RatioY, 'Media/FrmGraph/Plus/')
        self.BtnAjout.CanvasBtn.bind('<ButtonRelease-1>', self.AjoutCourbe)
        self.BtnSupp = BtnAction(self.CanvasFrmFond, int(self.SX * 0.98), int(self.SY * 0.03), self.RatioX * 0.5,
                                 self.RatioY * 0.5, 'Media/FrmGraph/BtnSupp/')
        self.BtnSupp.CanvasBtn.bind('<ButtonRelease-1>', self.SuppCourbe)

        self.ListCol = []
        for i in range(self.MainAppli.Tableur.NCol - 1):
            self.ListCol.append(self.MainAppli.Tableur.TabLabelNCol[i]['text'])

        self.ListeAxeX = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.04), values=self.ListCol)
        self.CanvasFrmFond.create_window(int(self.SX * 0.65), int(self.SY * 0.33), anchor=tk.CENTER,
                                         window=self.ListeAxeX)
        self.ListeAxeX.bind("<<ComboboxSelected>>", self.ModifAxes)
        self.ListeAxeY = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.04), values=self.ListCol)
        self.CanvasFrmFond.create_window(int(self.SX * 0.2), int(self.SY * 0.18), anchor=tk.CENTER,
                                         window=self.ListeAxeY)
        self.ListeAxeY.bind("<<ComboboxSelected>>", self.ModifAxes)

        if len(self.ListCol) > 0:
            self.ListeAxeX.set(self.ListCol[0])
            if len(self.ListCol) > 1:
                self.ListeAxeY.set(self.ListCol[1])
            else:
                self.ListeAxeY.set(self.ListCol[0])

        self.LabelPosAxeY = LabelInCanvas(self.CanvasFrmFond, 'Position :', '#F7F7F7', FontLabel(SizeFont),
                                          self.SX * 0.045, self.SY * 0.21)
        self.ListePosAxeY = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.02), values=['Gauche', 'Droite'])
        self.ListePosAxeY.config(font=FontLabel(SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.275), int(self.SY * 0.22), anchor=tk.CENTER,
                                         window=self.ListePosAxeY)
        self.ListePosAxeY.current(0)

        self.LabelEchelleX = LabelInCanvas(self.CanvasFrmFond, "Echelle de l'axe des abscisses", '#F7F7F7',
                                           FontLabelTitre(10), self.SX * 0.05, self.SY * 0.38)
        self.Xmin = DataEntry(self.CanvasFrmFond, '. Axe X - Valeur minimale : ', '#F7F7F7', FontLabel(SizeFont),
                              int(self.SX * 0.11), int(self.SY * 0.43), int(self.SX * 0.03), 4.7)
        self.Xmin.Val.set(str(self.MainAppli.Graph.MinX).replace('.', ','))

        self.Xmax = DataEntry(self.CanvasFrmFond, '. Axe X - Valeur maximale : ', '#F7F7F7', FontLabel(SizeFont),
                              int(self.SX * 0.11), int(self.SY * 0.48), int(self.SX * 0.03), 4.7)
        self.Xmax.Val.set(str(self.MainAppli.Graph.MaxX).replace('.', ','))

        self.LabelEchelleY = LabelInCanvas(self.CanvasFrmFond, "Echelle de l'axe des ordonnées", '#F7F7F7',
                                           FontLabelTitre(10), self.SX * 0.05, self.SY * 0.53)
        self.Ymin = DataEntry(self.CanvasFrmFond, '. Axe Y - Valeur minimale : ', '#F7F7F7', FontLabel(SizeFont),
                              int(self.SX * 0.11), int(self.SY * 0.58), int(self.SX * 0.03), 4.7)
        self.Ymin.Val.set(str(self.MainAppli.Graph.MinY).replace('.', ','))

        self.Ymax = DataEntry(self.CanvasFrmFond, '. Axe Y - Valeur maximale : ', '#F7F7F7', FontLabel(SizeFont),
                              int(self.SX * 0.11), int(self.SY * 0.63), int(self.SX * 0.03), 4.7)
        self.Ymax.Val.set(str(self.MainAppli.Graph.MaxY).replace('.', ','))

        self.LabelStyle = LabelInCanvas(self.CanvasFrmFond, "Style de courbe", '#F7F7F7',
                                        FontLabelTitre(10), self.SX * 0.05, self.SY * 0.7)
        self.LabelStyleLine = LabelInCanvas(self.CanvasFrmFond, '. Style de ligne :', '#F7F7F7', FontLabel(SizeFont),
                                            self.SX * 0.1, self.SY * 0.75)
        self.LabelStyleCol = LabelInCanvas(self.CanvasFrmFond, '. Couleur :', '#F7F7F7', FontLabel(SizeFont),
                                           self.SX * 0.1, self.SY * 0.8)
        self.LabelStyleSymb = LabelInCanvas(self.CanvasFrmFond, '. Symboles :', '#F7F7F7', FontLabel(SizeFont),
                                            self.SX * 0.1, self.SY * 0.85)
        self.LabelStyleSize = LabelInCanvas(self.CanvasFrmFond, '. Taille :', '#F7F7F7', FontLabel(SizeFont),
                                            self.SX * 0.7, self.SY * 0.85)
        self.ListeStyle = ['Pas de ligne', 'Ligne continue', 'Tirets', 'Ligne en pointillé', 'Tirets points']
        self.ListeDerStyle = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.04), values=self.ListeStyle)
        self.CanvasFrmFond.create_window(int(self.SX * 0.49), int(self.SY * 0.76), anchor=tk.CENTER,
                                         window=self.ListeDerStyle)
        self.ListeDerStyle.current(0)

        self.ListeCouleur = ['Bleu', 'Rouge', 'Vert', 'Cyan', 'Magenta', 'Jaune', 'Noir']
        self.ListeDerCouleur = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.04), values=self.ListeCouleur)
        self.CanvasFrmFond.create_window(int(self.SX * 0.49), int(self.SY * 0.81), anchor=tk.CENTER,
                                         window=self.ListeDerCouleur)
        self.ListeDerCouleur.current(0)

        self.ListeSymb = ['Plus', 'Cercle', 'Croix', 'Point', 'Etoile']
        self.ListeDerSymb = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.04), values=self.ListeSymb)
        self.CanvasFrmFond.create_window(int(self.SX * 0.49), int(self.SY * 0.86), anchor=tk.CENTER,
                                         window=self.ListeDerSymb)
        self.ListeDerSymb.current(0)

        self.ListSize = list(np.arange(1, 20, 1))
        self.ListeDerSize = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.01), values=self.ListSize)
        self.CanvasFrmFond.create_window(int(self.SX * 0.88), int(self.SY * 0.86), anchor=tk.CENTER,
                                         window=self.ListeDerSize)
        self.ListeDerSize.current(7)

        self.BtnAppliquer = tk.Button(self.CanvasFrmFond, text='Appliquer', command=self.Appliquer)
        self.CanvasFrmFond.create_window(int(self.SX * 0.8), int(self.SY * 0.92),
                                         anchor=tk.CENTER, window=self.BtnAppliquer)

        self.MenuOnglets = MenuOnglets(self.CanvasFrmFond, int(self.SX * 0.5), int(self.SY * 0.983), self.RatioX,
                                       self.RatioY, 0, 'Paramètres', 'Modélisation', 'Tableur', SizeFont + 2)

        for i in range(3):
            def GestEvt(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.MenuOnglets.ListCanvasMenu[i].bind('<Button-1>', GestEvt)

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

    def Appliquer(self):
        self.SavePara()
        self.MainAppli.Graph.Graph.AffichCourbes()

    def ClicOnMenu(self, _, j):
        self.MenuOnglets.InitOnglets2()
        self.MenuOnglets.ListCanvasMenu[j].itemconfig(self.MenuOnglets.ListImgMenu[j],
                                                      image=self.MenuOnglets.ListMenu[j][2])
        self.MenuOnglets.MenuSelected[j] = True
        if j == 1:
            self.MainAppli.Graph.BtnModel.CanvasBtn.itemconfig(self.MainAppli.Graph.BtnModel.ImgCanvasBtn,
                                                               image=self.MainAppli.Graph.BtnModel.ImgBtn[1])
            self.MainAppli.Graph.BtnPara.CanvasBtn.itemconfig(self.MainAppli.Graph.BtnPara.ImgCanvasBtn,
                                                              image=self.MainAppli.Graph.BtnPara.ImgBtn[0])
            self.MainAppli.Graph.AffichModel(_)
        elif j == 2:
            self.MainAppli.Graph.BtnPara.CanvasBtn.itemconfig(self.MainAppli.Graph.BtnPara.ImgCanvasBtn,
                                                              image=self.MainAppli.Graph.BtnPara.ImgBtn[0])
            self.MainAppli.Graph.BtnTableur.CanvasBtn.itemconfig(self.MainAppli.Graph.BtnTableur.ImgCanvasBtn,
                                                                 image=self.MainAppli.Graph.BtnTableur.ImgBtn[1])
            self.MainAppli.Graph.AffichTableur()
            self.MainAppli.Graph.TabShow = True

    def MoveOnCanvas(self, _):
        for i in range(3):
            if not self.MenuOnglets.MenuSelected[i]:
                self.MenuOnglets.ListCanvasMenu[i].itemconfig(self.MenuOnglets.ListImgMenu[i],
                                                              image=self.MenuOnglets.ListMenu[i][0])

    def ModifAxes(self, _):
        self.ModifAxe = True

    def AjoutCourbe(self, _):
        self.BtnAjout.CanvasBtn.itemconfig(self.BtnAjout.ImgCanvasBtn, image=self.BtnAjout.ImgBtn[0])
        if self.MainAppli.Graph.NCourbe < len(self.ListCol) - 1 and self.MainAppli.Graph.NCourbe < 5:
            self.MainAppli.Graph.NCourbe = self.MainAppli.Graph.NCourbe + 1
            self.NCourbeSelect = self.MainAppli.Graph.NCourbe
            self.MainAppli.Graph.NCourbeSelect = self.NCourbeSelect
            self.ListCourbe.append('Courbe ' + str(self.MainAppli.Graph.NCourbe))
            self.ListeCourbe.config(value=self.ListCourbe)
            self.ListeCourbe.current(self.NCourbeSelect - 1)
            self.ListeAxeY.set(self.ListCol[DeterminIndex(self.MainAppli.Graph.ListCourbeAxeY)])
            self.ListeAxeX.config(state='disabled')
            self.ListeDerCouleur.current(DeterminIndex(self.MainAppli.Graph.ListCourbeColor))
            self.ListeDerSymb.current(DeterminIndex(self.MainAppli.Graph.ListCourbeSymb))
            self.ListePosAxeY.current(1)
            self.ListeDerSize.current(7)
            self.ListeDerStyle.current(0)

            self.IndexColY = self.ListCol.index(self.ListeAxeY.get())
            self.IndexColX = self.ListCol.index(self.ListeAxeX.get())
            X, Y = self.MainAppli.Graph.TracePoints(self.IndexColX, self.IndexColY)
            MaxY = FindMax(Y)
            MaxY = round(MaxY * 1.1, 1)
            MinY = FindMin(Y)
            if MinY != 0:
                MinY = round(MinY * 0.9, 1)
            self.Ymax.Val.set(str(MaxY).replace('.', ','))
            self.Ymin.Val.set(str(MinY).replace('.', ','))

            self.MainAppli.Graph.ListX.append(X)
            self.MainAppli.Graph.ListY.append(Y)

            self.MainAppli.Graph.ListCourbeAxeX.append(self.ListeAxeX.current())
            self.MainAppli.Graph.ListCourbeAxeY.append(self.ListeAxeY.current())
            self.MainAppli.Graph.ListCourbePos.append(self.ListePosAxeY.current())
            self.MainAppli.Graph.ListCourbeMinX.append(float(self.Xmin.Val.get().replace(',', '.')))
            self.MainAppli.Graph.ListCourbeMaxX.append(float(self.Xmax.Val.get().replace(',', '.')))
            self.MainAppli.Graph.ListCourbeMinY.append(float(self.Ymin.Val.get().replace(',', '.')))
            self.MainAppli.Graph.ListCourbeMaxY.append(float(self.Ymax.Val.get().replace(',', '.')))
            self.MainAppli.Graph.ListCourbeStyle.append(self.ListeDerStyle.current())
            self.MainAppli.Graph.ListCourbeColor.append(self.ListeDerCouleur.current())
            self.MainAppli.Graph.ListCourbeSymb.append(self.ListeDerSymb.current())
            self.MainAppli.Graph.ListCourbeTailleSymb.append(self.ListeDerSize.current())
            self.MainAppli.Graph.ListEquation.append('')
            self.MainAppli.Graph.ListXmodel.append('')
            self.MainAppli.Graph.ListYmodel.append('')
            self.MainAppli.Graph.ListYmodel2.append('')
            self.MainAppli.Graph.NModel.append(0)
            self.MainAppli.Graph.ModelOrdre.append(0)
            self.MainAppli.Graph.ListValModel.append([])
            self.MainAppli.Graph.ListEcartModel.append([])
            self.MainAppli.Graph.Graph.AjoutCourbe()
            self.Appliquer()

    def SuppCourbe(self, evt):
        self.BtnSupp.CanvasBtn.itemconfig(self.BtnSupp.ImgCanvasBtn, image=self.BtnSupp.ImgBtn[0])
        if self.MainAppli.Graph.NCourbe == 1:
            self.MainAppli.Graph.CacheFrmGraph(evt)
        else:
            del self.MainAppli.Graph.ListCourbeAxeX[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeAxeY[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbePos[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeMinX[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeMaxX[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeMinY[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeMaxY[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeStyle[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeColor[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeSymb[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListCourbeTailleSymb[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListEquation[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListXmodel[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListYmodel[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListYmodel2[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.NModel[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ModelOrdre[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListValModel[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListEcartModel[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListX[self.NCourbeSelect - 1]
            del self.MainAppli.Graph.ListY[self.NCourbeSelect - 1]
            self.MainAppli.Graph.Graph.EffaceCourbes()
            self.MainAppli.Graph.Graph.EffaceLegends()
            del self.MainAppli.Graph.Graph.ListModelsLegend[self.NCourbeSelect - 1]
            self.NCourbeSelect = self.NCourbeSelect - 1
            if self.NCourbeSelect == 0:
                self.NCourbeSelect = 1
            self.MainAppli.Graph.NCourbe = self.MainAppli.Graph.NCourbe - 1
            self.MainAppli.Graph.NCourbeSelect = self.NCourbeSelect
            self.ListCourbe = []
            for i in range(self.MainAppli.Graph.NCourbe):
                self.ListCourbe.append('Courbe ' + str(i + 1))
            self.ListeCourbe.config(value=self.ListCourbe)
            self.ListeCourbe.current(self.NCourbeSelect - 1)
            self.ChargePara(evt)
            self.MainAppli.Graph.Graph.AffichCourbes()

    def SavePara(self):
        self.MainAppli.Graph.ListCourbeAxeX[self.NCourbeSelect - 1] = self.ListeAxeX.current()
        self.MainAppli.Graph.ListCourbeAxeY[self.NCourbeSelect - 1] = self.ListeAxeY.current()

        if self.ModifAxe:
            self.IndexColY = self.ListCol.index(self.ListeAxeY.get())
            self.IndexColX = self.ListCol.index(self.ListeAxeX.get())
            X, Y = self.MainAppli.Graph.TracePoints(self.IndexColX, self.IndexColY)
            MaxX = FindMax(X)
            MaxX = round(MaxX * 1.1, 1)
            MinX = FindMin(X)
            if MinX != 0:
                MinX = round(MinX * 0.9, 1)
            self.Xmax.Val.set(str(MaxX).replace('.', ','))
            self.Xmin.Val.set(str(MinX).replace('.', ','))
            MaxY = FindMax(Y)
            MaxY = round(MaxY * 1.1, 1)
            MinY = FindMin(Y)
            if MinY != 0:
                MinY = round(MinY * 0.9, 1)
            self.Ymax.Val.set(str(MaxY).replace('.', ','))
            self.Ymin.Val.set(str(MinY).replace('.', ','))
            self.MainAppli.Graph.ListX[self.NCourbeSelect - 1] = X
            self.MainAppli.Graph.ListY[self.NCourbeSelect - 1] = Y
            self.ModifAxe = False

        self.MainAppli.Graph.ListCourbePos[self.NCourbeSelect - 1] = self.ListePosAxeY.current()
        self.MainAppli.Graph.ListCourbeMinX[self.NCourbeSelect - 1] = float(self.Xmin.Val.get().replace(',', '.'))
        self.MainAppli.Graph.ListCourbeMaxX[self.NCourbeSelect - 1] = float(self.Xmax.Val.get().replace(',', '.'))
        self.MainAppli.Graph.ListCourbeMinY[self.NCourbeSelect - 1] = float(self.Ymin.Val.get().replace(',', '.'))
        self.MainAppli.Graph.ListCourbeMaxY[self.NCourbeSelect - 1] = float(self.Ymax.Val.get().replace(',', '.'))
        self.MainAppli.Graph.ListCourbeStyle[self.NCourbeSelect - 1] = self.ListeDerStyle.current()
        self.MainAppli.Graph.ListCourbeColor[self.NCourbeSelect - 1] = self.ListeDerCouleur.current()
        self.MainAppli.Graph.ListCourbeSymb[self.NCourbeSelect - 1] = self.ListeDerSymb.current()
        self.MainAppli.Graph.ListCourbeTailleSymb[self.NCourbeSelect - 1] = self.ListeDerSize.current()

    def ChargePara(self, _):
        self.NCourbeSelect = self.ListeCourbe.current() + 1
        self.MainAppli.Graph.NCourbeSelect = self.NCourbeSelect
        self.ListeAxeX.current(self.MainAppli.Graph.ListCourbeAxeX[self.NCourbeSelect - 1])
        self.ListeAxeY.current(self.MainAppli.Graph.ListCourbeAxeY[self.NCourbeSelect - 1])
        self.ListePosAxeY.current(self.MainAppli.Graph.ListCourbePos[self.NCourbeSelect - 1])
        self.Xmin.Val.set(self.MainAppli.Graph.ListCourbeMinX[self.NCourbeSelect - 1])
        self.Xmax.Val.set(self.MainAppli.Graph.ListCourbeMaxX[self.NCourbeSelect - 1])
        self.Ymin.Val.set(self.MainAppli.Graph.ListCourbeMinY[self.NCourbeSelect - 1])
        self.Ymax.Val.set(self.MainAppli.Graph.ListCourbeMaxY[self.NCourbeSelect - 1])
        self.ListeDerStyle.current(self.MainAppli.Graph.ListCourbeStyle[self.NCourbeSelect - 1])
        self.ListeDerCouleur.current(self.MainAppli.Graph.ListCourbeColor[self.NCourbeSelect - 1])
        self.ListeDerSymb.current(self.MainAppli.Graph.ListCourbeSymb[self.NCourbeSelect - 1])
        self.ListeDerSize.current(self.MainAppli.Graph.ListCourbeTailleSymb[self.NCourbeSelect - 1])
        self.Appliquer()


class FrmModelGraph(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.Container = container
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.TypeModelPredef = 0
        self.ModelPredef = None
        self.ModelResult = None
        self.TextExpress = None

        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="Graphes - "
                                                                                                "Modélisation")
        self.LabelTitre = LabelInCanvas(self.CanvasFrmFond, 'Modélisation Y = F(X)', '#F7F7F7',
                                        FontLabelTitre(10), self.SX * 0.05, self.SY * 0.038)

        self.ListCourbe = []
        for i in range(self.MainAppli.NCourbe):
            self.ListCourbe.append('Courbe ' + str(i + 1))
        self.ListeCourbe = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.022), values=self.ListCourbe)
        self.ListeCourbe.config(font=FontLabel(self.MainAppli.MainAppli.ParaGraph.SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.88), int(self.SY * 0.03), anchor=tk.CENTER,
                                         window=self.ListeCourbe)
        self.ListeCourbe.current(self.MainAppli.NCourbeSelect - 1)
        self.ListeCourbe.bind("<<ComboboxSelected>>", self.SelectCourbeToModel)

        self.FrameModel = tk.Frame(self.CanvasFrmFond, bg='#F7F7F7')
        self.CanvasFrmFond.create_window(int(self.SX * 0.5), int(self.SY * 0.48), anchor=tk.CENTER,
                                         window=self.FrameModel)
        self.CanvasModel = CanvasApp(self.FrameModel, width=int(self.SX * 0.98), height=int(self.SY * 0.84),
                                     scrollregion=(0, 0, int(self.SX), int(self.SY * 1.1)), bg='#F7F7F7')
        vbar = tk.Scrollbar(self.FrameModel, orient=tk.VERTICAL)
        vbar.pack(side=tk.RIGHT, fill=tk.Y)
        vbar.config(command=self.CanvasModel.yview)
        self.CanvasModel.config(yscrollcommand=vbar.set)
        self.CanvasModel.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)

        self.ListCanvasModel = []
        self.ImgModelLin, wsize, hsize, self.CanvasModelLin, self.ImgCanvasModelLin = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Lineaire/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.1), 0)
        self.ListCanvasModel.append(self.CanvasModelLin)

        self.ImgModelAff, wsize, hsize, self.CanvasModelAff, self.ImgCanvasModelAff = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Affine/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.25), 0)
        self.ListCanvasModel.append(self.CanvasModelAff)

        self.ImgModelPoly, wsize, hsize, self.CanvasModelPoly, self.ImgCanvasModelPoly = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Polynome/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.4), 0)
        self.ListCanvasModel.append(self.CanvasModelAff)

        self.ImgModelExp, wsize, hsize, self.CanvasModelExp, self.ImgCanvasModelExp = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Exp/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.55), 0)
        self.ListCanvasModel.append(self.CanvasModelExp)

        self.ImgModelLog, wsize, hsize, self.CanvasModelLog, self.ImgCanvasModelLog = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Logarithme/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.7), 0)
        self.ListCanvasModel.append(self.CanvasModelLog)

        self.ImgModelPuissance, wsize, hsize, self.CanvasModelPuissance, self.ImgCanvasModelPuissance = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Puissance/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY * 0.85), 0)
        self.ListCanvasModel.append(self.CanvasModelPuissance)

        self.ImgModelPredef, wsize, hsize, self.CanvasModelPredef, self.ImgCanvasModelPredef = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Predef/', self.RatioX, self.RatioY, self.CanvasModel,
            int(self.SX * 0.25), int(self.SY), 0)
        self.ListCanvasModel.append(self.CanvasModelPredef)

        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.Nconfig, 'MG'))
        self.LabelPara1 = tk.Label(self.CanvasFrmFond, text='', bg='#F7F7F7', font=FontLabel(SizeFont))
        self.CanvasModel.create_window(int(self.SX * 0.5), int(self.SY * 0.92), anchor=tk.NW,
                                       window=self.LabelPara1)
        self.LabelPara2 = tk.Label(self.CanvasFrmFond, text='', bg='#F7F7F7', font=FontLabel(SizeFont))
        self.CanvasModel.create_window(int(self.SX * 0.5), int(self.SY * 0.94), anchor=tk.NW,
                                       window=self.LabelPara2)

        self.varchoix = []
        self.CaseChoixModel = []
        self.TextModel = ['Linéaire', 'Affine', 'Polynomiale', 'Exponentielle', 'Logarithmique', 'Puissance',
                          'Model prédéfini']
        self.ListIma, wsize, hsize = ChargeDossierImg('Media/FrmGraph/FrmModelGraph/Equations/', self.RatioX * 0.7,
                                                      self.RatioY * 0.7)
        for i in range(7):
            self.varchoix.append(tk.IntVar())

            def GestEvt(j=i):
                return self.onClickChoix(j)

            def GestEVT2(_, j=i):
                return self.onClickChoix2(j)

            self.ListCanvasModel[i].bind('<ButtonPress-1>', GestEVT2)
            ChangeCursor(self.ListCanvasModel[i])

            self.CaseChoixModel.append(CaseACocher(self.CanvasModel, self.TextModel[i], font=FontLabel2(11),
                                                   variable=self.varchoix[i], bg='#F7F7F7', command=GestEvt))
            self.CanvasModel.create_window(int(self.SX * 0.5), int(self.SY * 0.08 + i * (self.SY * 0.15)),
                                           anchor=tk.W, window=self.CaseChoixModel[i])

            if i != 6 and i != 2:
                self.CanvasModel.create_image(int(self.SX * 0.65), int(self.SY * 0.12) + i * int(self.SY * 0.15),
                                              anchor=tk.CENTER, image=self.ListIma[i])
            elif i == 6:
                self.ImgEquaPredef, wsize, hsize, self.CanvasEquaPredef, self.ImgCanvasEquaPredef = CanInWindow(
                    'Media/FrmGraph/FrmModelGraph/EquaPredef/', self.RatioX * 0.7, self.RatioY * 0.7,
                    self.CanvasModel, int(self.SX * 0.65), int(self.SY * 1.02), 0)
            else:
                self.ImgEquaPolyn, wsize, hsize, self.CanvasEquaPolyn, self.ImgCanvasEquaPolyn = CanInWindow(
                    'Media/FrmGraph/FrmModelGraph/EquaPolyn/', self.RatioX * 0.55, self.RatioY * 0.55,
                    self.CanvasModel, int(self.SX * 0.7), int(self.SY * 0.42), 0)
                self.CanvasModel.create_text(int(self.SX * 0.6), int(self.SY * 0.45),
                                             anchor=tk.E, text='Ordre :')
                self.ListOrdre = ["1", "2", "3"]
                self.ListeOrdre = ListeDeroulante(self.CanvasFrmFond, '2', values=self.ListOrdre)
                self.CanvasModel.create_window(int(self.SX * 0.65), int(self.SY * 0.45), anchor=tk.CENTER,
                                               window=self.ListeOrdre)
                self.ListeOrdre.current(1)

        self.BtnAppliquer = tk.Button(self.CanvasFrmFond, text='Appliquer', command=self.Appliquer)
        self.CanvasFrmFond.create_window(int(self.SX * 0.8), int(self.SY * 0.92),
                                         anchor=tk.CENTER, window=self.BtnAppliquer)

        self.MenuOnglets = MenuOnglets(self.CanvasFrmFond, int(self.SX * 0.5), int(self.SY * 0.983), self.RatioX,
                                       self.RatioY, 1, 'Paramètres', 'Modélisation', 'Tableur',
                                       self.MainAppli.MainAppli.ParaGraph.SizeFont + 2)

        for i in range(3):
            def GestEvt(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.MenuOnglets.ListCanvasMenu[i].bind('<Button-1>', GestEvt)

        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)

        self.MainAppli.MainAppli.Graph.lift()
        self.lift()
        self.CanvasFrmFond.pack()

        if self.MainAppli.MainAppli.Graph.ListValModel[self.ListeCourbe.current()]:
            self.ModelResult = FrmModelResult(self.Container, self.RatioX, self.RatioY, self.MainAppli)

    def onClickChoix(self, j):
        for i in range(len(self.CaseChoixModel)):
            self.varchoix[i].set(0)
        self.varchoix[j].set(1)

    def onClickChoix2(self, j):
        self.onClickChoix(j)
        if j == 6:
            self.ModelPredef = FrmModelDef(self.Container, self.RatioX, self.RatioY, self.MainAppli)

    def Appliquer(self):
        self.MainAppli.OrdrePolyn = self.ListeOrdre.current() + 1
        self.MainAppli.ActionAffichModel()
        if self.MainAppli.MainAppli.Graph.ListEquation[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] != '':
            self.ModelResult = FrmModelResult(self.Container, self.RatioX, self.RatioY, self.MainAppli)

    def ClicOnMenu(self, _, j):
        self.MenuOnglets.InitOnglets2()
        self.MenuOnglets.ListCanvasMenu[j].itemconfig(self.MenuOnglets.ListImgMenu[j],
                                                      image=self.MenuOnglets.ListMenu[j][2])
        self.MenuOnglets.MenuSelected[j] = True
        if j == 0:
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.InitOnglets2()
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListCanvasMenu[j].itemconfig(
                self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListImgMenu[j],
                image=self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListMenu[j][2])
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.MenuSelected[j] = True
            self.MainAppli.MainAppli.Graph.BtnModel.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnModel.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnModel.ImgBtn[0])
            self.MainAppli.MainAppli.Graph.BtnPara.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnPara.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnPara.ImgBtn[1])
            self.MainAppli.MainAppli.Graph.ModelGraph.destroy()
            self.MainAppli.MainAppli.Graph.ModelGraph = None
            self.MainAppli.MainAppli.Graph.ModelShow = False
            self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
            self.MainAppli.MainAppli.ParaGraph.lift()
            self.MainAppli.MainAppli.Graph.lift()
            self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                               text="Graphes - "
                                                                                                    "Paramètres")
        elif j == 2:
            self.MainAppli.MainAppli.Graph.BtnModel.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnModel.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnModel.ImgBtn[0])
            self.MainAppli.MainAppli.Graph.BtnTableur.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnTableur.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnTableur.ImgBtn[1])
            self.MainAppli.MainAppli.Graph.ModelGraph.destroy()
            self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
            self.MainAppli.MainAppli.ParaGraph.lift()
            self.MainAppli.MainAppli.Graph.ModelGraph = None
            self.MainAppli.MainAppli.Graph.ModelShow = False
            self.MainAppli.MainAppli.Graph.TabShow = True
            self.MainAppli.MainAppli.Graph.AffichTableur()

    def MoveOnCanvas(self, _):
        for i in range(3):
            if not self.MenuOnglets.MenuSelected[i]:
                self.MenuOnglets.ListCanvasMenu[i].itemconfig(self.MenuOnglets.ListImgMenu[i],
                                                              image=self.MenuOnglets.ListMenu[i][0])

    def SelectCourbeToModel(self, _):
        self.MainAppli.MainAppli.Graph.NCourbeSelect = self.ListeCourbe.current() + 1
        if self.ModelResult is not None:
            self.ModelResult.destroy()
        if self.MainAppli.MainAppli.Graph.ListValModel[self.ListeCourbe.current()]:
            self.ModelResult = FrmModelResult(self.Container, self.RatioX, self.RatioY, self.MainAppli)


class FrmModelDef(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY

        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="Graphes - "
                                                                                                "Modélisation "
                                                                                                "prédéfinies")
        SizeFont = int(ConfigResolution(self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.Nconfig, 'G1'))
        self.LabelTitre = LabelInCanvas(self.CanvasFrmFond, 'Modélisation Y = F(X)', '#F7F7F7',
                                        FontLabelTitre(10), self.SX * 0.05, self.SY * 0.03)

        self.ListCanvasModelPredef = []
        self.ListImgModelPredef = []
        self.ListImgCanvasModelPredef = []
        self.LabelTitre = []
        self.LabelTitreText = ['Dipole RC - Charge C', 'Dipole RC - Décharge C',
                               'Relation simplifiée de \n Steinhart-Hart', 'Modèle personnel']
        self.ListIma, wsize, hsize = ChargeDossierImg('Media/FrmGraph/FrmModelGraph/EquaPredef/', self.RatioX * 0.7,
                                                      self.RatioY * 0.7)
        Yd = 0
        for i in range(4):
            self.ImgModelPredef, wsize, hsize, self.CanvasModelPredef, self.ImgCanvasModelPredef = CanInWindow(
                'Media/FrmGraph/FrmModelGraph/Predef/', self.RatioX, self.RatioY, self.CanvasFrmFond,
                int(self.SX * 0.25), int(self.SY * 0.15) + i * int(self.SY * 0.19), i)
            if i == 3:
                Yd = 1
            elif i == 2:
                Yd = -1
            self.LabelTitre.append(LabelInCanvas(self.CanvasFrmFond, self.LabelTitreText[i], '#F7F7F7',
                                                 FontLabel2(10), int(self.SX * 0.5),
                                                 int(self.SY * 0.11) + i * int(self.SY * 0.18) +
                                                 Yd * int(self.SY * 0.02)))

            self.ListCanvasModelPredef.append(self.CanvasModelPredef)
            self.ListImgModelPredef.append(self.ImgModelPredef)
            self.ListImgCanvasModelPredef.append(self.ImgCanvasModelPredef)
            ChangeCursor(self.ListCanvasModelPredef[i])

            def GestEvt(_, j=i):
                return self.ActionBtn(j)

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

            if i < 3:
                self.CanvasFrmFond.create_image(int(self.SX * 0.65), int(self.SY * 0.17) + i * int(self.SY * 0.175),
                                                anchor=tk.CENTER, image=self.ListIma[i])

        self.LabelR0 = LabelInCanvas(self.CanvasFrmFond, 'Ro (Ohms) = ', '#F7F7F7', FontLabel(SizeFont),
                                     int(self.SX * 0.5), int(self.SY * 0.55))
        self.R0 = tk.StringVar()
        self.R0.set('')
        self.EntryR0 = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.02), font=FontLabel(SizeFont),
                                textvariable=self.R0)
        self.CanvasFrmFond.create_window(int(self.SX * 0.71), int(self.SY * 0.55), anchor=tk.NW,
                                         window=self.EntryR0)
        self.EntryR0.bind('<Return>', self.EnterPara)
        self.LabelT0 = LabelInCanvas(self.CanvasFrmFond, 'To (Kelvins) = ', '#F7F7F7', FontLabel(SizeFont),
                                     int(self.SX * 0.5), int(self.SY * 0.58))
        self.T0 = tk.StringVar()
        self.T0.set('')
        self.EntryT0 = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.02), font=FontLabel(SizeFont),
                                textvariable=self.T0)
        self.EntryT0.bind('<Return>', self.EnterPara)
        self.CanvasFrmFond.create_window(int(self.SX * 0.71), int(self.SY * 0.58), anchor=tk.NW,
                                         window=self.EntryT0)

        self.CanvasFrmFond.create_text(int(self.SX * 0.5), int(self.SY * 0.72), anchor=tk.W, font=FontLabel2(12),
                                       text='y =')
        self.Express = tk.StringVar()
        self.EntryExpress = tk.Entry(self.CanvasFrmFond, width=int(self.SX * 0.045), font=FontLabel(12),
                                     textvariable=self.Express)
        self.CanvasFrmFond.create_window(int(self.SX * 0.58), int(self.SY * 0.72), anchor=tk.W,
                                         window=self.EntryExpress)
        self.EntryExpress.bind('<Return>', self.EnterExpress)
        self.CanvasFrmFond.create_text(int(self.SX * 0.5), int(self.SY * 0.755), anchor=tk.W, font=FontLabel(SizeFont),
                                       text='Paramètres Y = F(X) :')
        self.ListPara = ['a', 'a,b', 'a,b,c', 'a,b,c,d']
        self.ListePara = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.018), values=self.ListPara)
        self.CanvasFrmFond.create_window(int(self.SX * 0.82), int(self.SY * 0.755), anchor=tk.W,
                                         window=self.ListePara)
        self.ListePara.current(0)

        self.lift()
        self.CanvasFrmFond.pack()

    def ActionBtn(self, j):
        if j != 2 and j != 3:
            self.MainAppli.ModelGraph.TypeModelPredef = j
            self.MainAppli.ModelGraph.CanvasModelPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasModelPredef,
                                                                   image=self.MainAppli.ModelGraph.ImgModelPredef[j])
            self.MainAppli.ModelGraph.CanvasEquaPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasEquaPredef,
                                                                  image=self.MainAppli.ModelGraph.ImgEquaPredef[j])
            self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                               text="Graphes - "
                                                                                                    "Modélisation")
            self.destroy()
        elif j == 2:
            self.EntryR0.focus_set()
        else:
            self.EntryExpress.focus_set()

    def EnterPara(self, _):
        if self.R0.get() != '' and self.T0.get() != '':
            self.MainAppli.Para1 = float(self.R0.get())
            self.MainAppli.ModelGraph.LabelPara1.configure(text='Ro (Ohms) = ' + self.R0.get())
            self.MainAppli.Para2 = float(self.T0.get().replace(',', '.'))
            self.MainAppli.ModelGraph.LabelPara2.configure(text='To (Kelvins) = ' + self.T0.get().replace('.', ','))
            self.MainAppli.ModelGraph.TypeModelPredef = 2
            self.MainAppli.ModelGraph.CanvasModelPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasModelPredef,
                                                                   image=self.MainAppli.ModelGraph.ImgModelPredef[2])
            self.MainAppli.ModelGraph.CanvasEquaPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasEquaPredef,
                                                                  image=self.MainAppli.ModelGraph.ImgEquaPredef[2])
            self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                               text="Graphes - "
                                                                                                    "Modélisation")
            self.destroy()
        elif self.R0.get() != '':
            self.EntryT0.focus_set()
        else:
            self.EntryR0.focus_set()

    def EnterExpress(self, _):
        self.MainAppli.Express = self.Express.get().replace(' ', '')
        self.MainAppli.NExpress = self.ListePara.current() + 1
        self.MainAppli.ModelGraph.TypeModelPredef = 3
        self.MainAppli.ModelGraph.CanvasModelPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasModelPredef,
                                                               image=self.MainAppli.ModelGraph.ImgModelPredef[3])
        self.MainAppli.ModelGraph.CanvasEquaPredef.itemconfig(self.MainAppli.ModelGraph.ImgCanvasEquaPredef,
                                                              image=self.MainAppli.ModelGraph.ImgEquaPredef[3])
        if self.MainAppli.ModelGraph.TextExpress is not None:
            self.MainAppli.ModelGraph.CanvasEquaPredef.delete(self.MainAppli.ModelGraph.TextExpress)
        self.MainAppli.ModelGraph.TextExpress = self.MainAppli.ModelGraph.CanvasEquaPredef.create_text(
            int(self.MainAppli.ModelGraph.CanvasEquaPredef.winfo_width() / 2),
            int(self.MainAppli.ModelGraph.CanvasEquaPredef.winfo_height() / 2),
            anchor=tk.CENTER, font=FontLabel(12),
            text='y =' + self.Express.get().replace(' ', ''))
        self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                           text="Graphes - "
                                                                                                "Modélisation")
        self.destroy()


class FrmTableurGraph(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY

        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.ListCourbe = []
        for i in range(self.MainAppli.NCourbe):
            self.ListCourbe.append('Courbe ' + str(i + 1))
        self.ListeCourbe = ListeDeroulante(self.CanvasFrmFond, int(self.SX * 0.022), values=self.ListCourbe)
        self.ListeCourbe.config(font=FontLabel(self.MainAppli.MainAppli.ParaGraph.SizeFont))
        self.CanvasFrmFond.create_window(int(self.SX * 0.88), int(self.SY * 0.03), anchor=tk.CENTER,
                                         window=self.ListeCourbe)
        self.ListeCourbe.current(self.MainAppli.NCourbeSelect - 1)
        self.ListeCourbe.bind("<<ComboboxSelected>>", self.SelectCourbe)

        self.FrameTableur = tk.Frame(self.CanvasFrmFond)
        self.CanvasFrmFond.create_window(int(self.SX * 0.5), int(self.SY * 0.52), anchor=tk.CENTER,
                                         window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(self.SX * 0.9),
                                                  int(self.SY * 0.87))
        self.scrollable_canvas.grid(row=1, column=1)

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

        self.TabLabelN = []
        self.TabLabelNCol = []
        self.TabLabels = []
        for r in range(len(self.MainAppli.MainAppli.Graph.ListX[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1])):
            self.TabLabelN.append(tk.Label(self.scrollable_canvas.interior, text=str(r + 1), relief=tk.RIDGE,
                                           width=int(self.SX * 0.01), bg='white', font=FontLabel2(10)))
            self.TabLabelN[r].grid(row=r + 1, column=0)
            ChangeCursor(self.TabLabelN[r])

            def GestEvt(evt, j=r):
                return self.SelectLineTab(evt, j)

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

            self.TabLabelCol = []
            for i in range(3):
                self.TabLabelNCol.append(
                    tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                             width=int(self.SX * 0.029), height=2, bg='white', font=FontLabel2(11)))
                self.TabLabelNCol[i].grid(row=0, column=i + 1)
                self.TabLabelCol.append(tk.Label(self.scrollable_canvas.interior, text='', relief=tk.RIDGE,
                                                 width=int(self.SX * 0.029), bg='white', font=FontLabel(11)))
                self.TabLabelCol[i].grid(row=r + 1, column=i + 1)
            self.TabLabels.append(self.TabLabelCol)

        self.TabLabelNCol[0]['text'] = \
            self.MainAppli.MainAppli.Graph.ListLabelAxe[
                self.MainAppli.MainAppli.Graph.ListCourbeAxeX[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]]
        self.TabLabelNCol[1]['text'] = \
            self.MainAppli.MainAppli.Graph.ListLabelAxe[
                self.MainAppli.MainAppli.Graph.ListCourbeAxeY[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]]
        if self.MainAppli.MainAppli.Graph.ListValModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]:
            self.TabLabelNCol[2]['text'] = \
                self.MainAppli.MainAppli.Graph.ListLabelAxe[
                    self.MainAppli.MainAppli.Graph.ListCourbeAxeY[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]] + \
                '\n modelisé(e)'
        for r in range(len(self.MainAppli.MainAppli.Graph.ListX[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1])):
            self.TabLabels[r][0]['text'] = \
                str(self.MainAppli.MainAppli.Graph.ListX[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][r]).replace(
                    '.', ',')
            self.TabLabels[r][1]['text'] = \
                str(self.MainAppli.MainAppli.Graph.ListY[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][r]).replace(
                    '.', ',')
            if self.MainAppli.MainAppli.Graph.ListValModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]:
                self.TabLabels[r][2]['text'] = \
                    str(round(self.MainAppli.MainAppli.Graph.ListYmodel2
                              [self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][r], 2)).replace('.', ',')

        self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                           text="Graphes - "
                                                                                                "Tableur")
        self.MenuOnglets = MenuOnglets(self.CanvasFrmFond, int(self.SX * 0.5), int(self.SY * 0.983), self.RatioX,
                                       self.RatioY, 2, 'Paramètres', 'Modélisation', 'Tableur',
                                       self.MainAppli.MainAppli.ParaGraph.SizeFont + 2)

        for i in range(3):
            def GestEvt(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.MenuOnglets.ListCanvasMenu[i].bind('<Button-1>', GestEvt)

        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)
        self.scrollable_canvas.canvas.bind('<Motion>', self.MoveOnCanvas)
        self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
        self.MainAppli.MainAppli.Graph.lift()
        self.lift()
        self.CanvasFrmFond.pack()

    def ClicOnMenu(self, _, j):
        self.MenuOnglets.InitOnglets2()
        self.MenuOnglets.ListCanvasMenu[j].itemconfig(self.MenuOnglets.ListImgMenu[j],
                                                      image=self.MenuOnglets.ListMenu[j][2])
        self.MenuOnglets.MenuSelected[j] = True
        if j == 0:
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.InitOnglets2()
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListCanvasMenu[j].itemconfig(
                self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListImgMenu[j],
                image=self.MainAppli.MainAppli.ParaGraph.MenuOnglets.ListMenu[j][2])
            self.MainAppli.MainAppli.ParaGraph.MenuOnglets.MenuSelected[j] = True
            self.MainAppli.MainAppli.Graph.BtnTableur.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnTableur.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnTableur.ImgBtn[0])
            self.MainAppli.MainAppli.Graph.BtnPara.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnPara.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnPara.ImgBtn[1])
            self.MainAppli.MainAppli.Graph.TableurGraph.destroy()
            self.MainAppli.MainAppli.Graph.TableurGraph = None
            self.MainAppli.MainAppli.Graph.TabShow = False
            self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
            self.MainAppli.MainAppli.ParaGraph.lift()
            self.MainAppli.MainAppli.Graph.lift()
            self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.CanvasFrmMain.itemconfigure('LegendePanneauD',
                                                                                               text="Graphes - "
                                                                                                    "Paramètres")
        elif j == 1:
            self.MainAppli.MainAppli.Graph.BtnTableur.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnTableur.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnTableur.ImgBtn[0])
            self.MainAppli.MainAppli.Graph.BtnModel.CanvasBtn.itemconfig(
                self.MainAppli.MainAppli.Graph.BtnModel.ImgCanvasBtn,
                image=self.MainAppli.MainAppli.Graph.BtnModel.ImgBtn[1])
            self.MainAppli.MainAppli.Graph.TableurGraph.destroy()
            self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
            self.MainAppli.MainAppli.ParaGraph.lift()
            self.MainAppli.MainAppli.Graph.lift()
            self.MainAppli.MainAppli.Graph.TableurGraph = None
            self.MainAppli.MainAppli.Graph.TabShow = False
            self.MainAppli.MainAppli.Graph.AffichModel(_)

    def MoveOnCanvas(self, _):
        for i in range(3):
            if not self.MenuOnglets.MenuSelected[i]:
                self.MenuOnglets.ListCanvasMenu[i].itemconfig(self.MenuOnglets.ListImgMenu[i],
                                                              image=self.MenuOnglets.ListMenu[i][0])

    def SelectCourbe(self, _):
        self.MainAppli.MainAppli.Graph.NCourbeSelect = self.ListeCourbe.current() + 1
        self.MAJTab(self.ListeCourbe.current())

    def MAJTab(self, NCourbe):
        self.TabLabelNCol[1]['text'] = \
            self.MainAppli.MainAppli.Graph.ListLabelAxe[self.MainAppli.MainAppli.Graph.ListCourbeAxeY[NCourbe]]
        for r in range(len(self.MainAppli.MainAppli.Graph.ListX[NCourbe])):
            self.TabLabels[r][1]['text'] = str(self.MainAppli.MainAppli.Graph.ListY[NCourbe][r]).replace('.', ',')
            if self.MainAppli.MainAppli.Graph.ListValModel[NCourbe]:
                self.TabLabels[r][2]['text'] = \
                    str(round(self.MainAppli.MainAppli.Graph.ListYmodel2[NCourbe][r], 2)).replace('.', ',')
            else:
                self.TabLabels[r][2]['text'] = ''

        if self.MainAppli.MainAppli.Graph.ListValModel[NCourbe]:
            self.TabLabelNCol[2]['text'] = \
                self.MainAppli.MainAppli.Graph.ListLabelAxe[
                    self.MainAppli.MainAppli.Graph.ListCourbeAxeY[NCourbe]] + '\n modelisé(e)'
        else:
            self.TabLabelNCol[2]['text'] = ''

    def SelectLine(self, NCourbe, X):
        self.UnSelectLine()
        Line = 0
        for r in range(len(self.MainAppli.MainAppli.Graph.ListX[NCourbe])):
            if self.TabLabels[r][0]['text'] == str(X).replace('.', ','):
                Line = r
                break
        self.TabLabelN[Line].config(bg='#E0E0E0')
        for i in range(3):
            self.TabLabels[Line][i].config(bg='#E0E0E0')

    def SelectLineTab(self, _, j):
        self.UnSelectLine()
        self.TabLabelN[j].config(bg='#E0E0E0')
        for i in range(3):
            self.TabLabels[j][i].config(bg='#E0E0E0')

        self.MainAppli.MainAppli.Graph.BtnCurseur.CanvasBtn.itemconfig(
            self.MainAppli.MainAppli.Graph.BtnCurseur.ImgCanvasBtn,
            image=self.MainAppli.MainAppli.Graph.BtnCurseur.ImgBtn[1])
        self.MainAppli.MainAppli.Graph.CurseurActif = True
        ChangeCursor(self.MainAppli.MainAppli.Graph.Graph.CanvasGraph)
        self.MainAppli.MainAppli.Graph.Graph.Xcur = self.MainAppli.MainAppli.Graph.ListX[
            self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][j]
        self.MainAppli.MainAppli.Graph.Graph.Ycur = self.MainAppli.MainAppli.Graph.ListY[
            self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][j]
        self.MainAppli.MainAppli.Graph.Graph.CanvasGraph.delete(self.MainAppli.MainAppli.Graph.Graph.TextX)
        self.MainAppli.MainAppli.Graph.Graph.CanvasGraph.delete(self.MainAppli.MainAppli.Graph.Graph.TextY)
        self.MainAppli.MainAppli.Graph.Graph.ActionAffichCurseur()

    def UnSelectLine(self):
        for j in range(len(self.TabLabelN)):
            self.TabLabelN[j].config(bg='white')
            for i in range(3):
                self.TabLabels[j][i].config(bg='white')


class FrmModelResult(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.RatioX = RatioX
        self.RatioY = RatioY

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmGraph/FrmModelGraph/Fond/01.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/FrmGraph/FrmModelGraph/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])

        Ypercent = ConfigResolution(self.MainAppli.MainAppli.MainAppli.MainAppli.MainAppli.Nconfig, 'GMR')
        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.753)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * Ypercent)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.LabelTitre = LabelInCanvas(self.CanvasFrmFond, 'Résultat de la modélisation Y = F(X)', '#F7F7F7',
                                        FontLabelTitre(11), self.SX * 0.05, self.SY * 0.03)

        self.ImgModel, wsize, hsize, self.CanvasModel, self.ImgCanvasModel = CanInWindow(
            'Media/FrmGraph/FrmModelGraph/Models/', self.RatioX, self.RatioY, self.CanvasFrmFond,
            int(self.SX * 0.5), int(self.SY * 0.18),
            self.MainAppli.MainAppli.Graph.NModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] - 1)

        LabelInCanvasC(self.CanvasFrmFond, self.MainAppli.MainAppli.Graph.ListLabelAxe[
            self.MainAppli.MainAppli.Graph.ListCourbeAxeX[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]],
                       '#F7F7F7', FontLabel(10), self.SX * 0.5, self.SY * 0.27)
        LabelInCanvasE(self.CanvasFrmFond, self.MainAppli.MainAppli.Graph.ListLabelAxe[
            self.MainAppli.MainAppli.Graph.ListCourbeAxeY[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]],
                       '#F7F7F7', FontLabel(10), self.SX * 0.3, self.SY * 0.18)

        self.ImgEqua, wsize, hsize, self.CanvasEqua, self.ImgCanvasEqua = CanInWindowW(
            'Media/FrmGraph/FrmModelGraph/EquaModels/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
            int(self.SX * 0.67), int(self.SY * 0.18), self.MainAppli.MainAppli.Graph.NModel[
                                                            self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] - 1)
        if self.MainAppli.MainAppli.Graph.NModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] == 3:
            self.ImgEquaPolyn, wsize, hsize, self.CanvasEquaPolyn, self.ImgCanvasEquaPolyn = CanInWindow(
                'Media/FrmGraph/FrmModelGraph/EquaModelPol/', self.RatioX * 0.7, self.RatioY * 0.7, self.CanvasFrmFond,
                int(self.SX * 0.5), int(self.SY * 0.3), self.MainAppli.MainAppli.Graph.ModelOrdre[
                                                                  self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] - 1)

        if self.MainAppli.MainAppli.Graph.NModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] == 10:
            self.CanvasFrmFond.create_text(int(self.SX * 0.5), int(self.SY * 0.3), anchor=tk.CENTER, font=FontLabel(12),
                                           text='y =' + self.MainAppli.MainAppli.Graph.Express)

        self.BtnAnnuler = tk.Button(self.CanvasFrmFond, text='Annuler', command=self.Annuler)
        self.CanvasFrmFond.create_window(int(self.SX * 0.8), int(self.SY * 0.92),
                                         anchor=tk.CENTER, window=self.BtnAnnuler)
        self.AffichValModel()
        self.lift()
        self.CanvasFrmFond.pack()

    def AffichValModel(self):
        listCoef = ['a', 'b', 'c', 'd']
        for i in range(len(self.MainAppli.MainAppli.Graph.ListValModel[
                               self.MainAppli.MainAppli.Graph.NCourbeSelect - 1])):
            self.CanvasFrmFond.create_text(int(self.SX * 0.1), int(self.SY * 0.34) + i * int(self.SY * 0.04),
                                           anchor=tk.W, font=FontLabel2(12),
                                           text=listCoef[i] + ' = ' + format(
                                               self.MainAppli.MainAppli.Graph.ListValModel[
                                                   self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][i], ".2E"))
        if len(self.MainAppli.MainAppli.Graph.ListValModel[
                   self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]) == 4:
            Ytext = int(self.SY * 0.52)
        else:
            Ytext = int(self.SY * 0.48)

        self.CanvasFrmFond.create_text(int(self.SX * 0.05), Ytext, anchor=tk.W, font=FontLabelTitre(11),
                                       text='Ecart expérience - modélisation')

        self.CanvasFrmFond.create_text(int(self.SX * 0.1), Ytext + int(self.SY * 0.05), anchor=tk.W, font=FontLabel(10),
                                       text='. Ecart moyen ' + self.MainAppli.MainAppli.Graph.ListLabelAxe[
                                           self.MainAppli.MainAppli.Graph.ListCourbeAxeY[
                                               self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]] + ' = ' +
                                            format(self.MainAppli.MainAppli.Graph.ListEcartModel[
                                                       self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][0], ".2E"))
        if len(self.MainAppli.MainAppli.Graph.ListEcartModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1]) == 2:
            self.CanvasFrmFond.create_text(int(self.SX * 0.1), int(self.SY * 0.56), anchor=tk.W, font=FontLabel(10),
                                           text='. Coefficient de corrélation linéaire = ' +
                                                str(round(self.MainAppli.MainAppli.Graph.ListEcartModel[
                                                              self.MainAppli.MainAppli.Graph.NCourbeSelect - 1][
                                                              1], 3)))

    def Annuler(self):
        self.MainAppli.MainAppli.Graph.ListEquation[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] = ''

        self.MainAppli.MainAppli.Graph.Graph.AffichModelCourbe([], [], self.MainAppli.MainAppli.Graph.NCourbeSelect - 1)
        self.MainAppli.MainAppli.Graph.Graph.ListModelsLegend[
            self.MainAppli.MainAppli.Graph.NCourbeSelect - 1].set_color('white')
        self.MainAppli.MainAppli.Graph.ListValModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] = []
        self.MainAppli.MainAppli.Graph.ListEcartModel[self.MainAppli.MainAppli.Graph.NCourbeSelect - 1] = []
        Model = False
        for i in range(len(self.MainAppli.MainAppli.Graph.ListEquation)):
            if self.MainAppli.MainAppli.Graph.ListEquation[i] != '':
                Model = True
                break
        self.MainAppli.MainAppli.Graph.Graph.AffichLegend()
        if not Model:
            self.MainAppli.MainAppli.Graph.Graph.Graph.legend_.remove()
            self.MainAppli.MainAppli.Graph.Graph.LegendActif = False
            self.MainAppli.MainAppli.Graph.Graph.graphfig.draw()
        self.destroy()
        self.MainAppli.MainAppli.MainAppli.MainAppli.parent.lift()
        self.MainAppli.lift()
        self.MainAppli.ModelGraph.lift()
