#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.20
#  in conjunction with Tcl version 8.6
#    Feb 18, 2019 11:55:48 AM -03  platform: Windows NT
#    Feb 19, 2019 09:09:42 AM -03  platform: Windows NT
"""
Created on Mon Feb 18 10:08:04 2019

@author: <NAME>
"""
import sys

import Controller as ctrl
import Model as md
import Estilos as es

import numpy as np
#from numpy import array, concatenate, ndarray, append, take, delete


import pandas as pd

from tkinter import filedialog, colorchooser, IntVar

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True 

def set_var():
    global conn, qtdMin, curvePlot, curvesList, cBoxList, md_dpv, validation
    conn = 0
    qtdMin = 0
    curvePlot = np.ndarray([])
    curvesList = np.ndarray([])
    cBoxList = np.ndarray([])
    md_dpv = md.dpv()
    validation = ctrl.validation(w, root)
    

def init(top, gui, *args, **kwargs):
    global w, top_level, root, font9
    w = gui
    top_level = top
    root = top
    #font9 = "-family {Segoe UI} -size 9 -weight bold -slant roman "  \
    #        "-underline 0 -overstrike 0"
    set_var()
    painelDPV()

def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None

if __name__ == '__main__':
    import VStat
    VStat.vp_start_gui()
    
##########  Funções ###########
def createCanvas():
    w.cv_curveGraph = tk.Canvas(w.fr_mainView)
    w.cv_curveGraph.place(relx=0.012, rely=0.119, relheight=0.857, relwidth=0.974)
    w.cv_curveGraph.configure(background="#ffffff")
    w.cv_curveGraph.configure(highlightbackground="#ffffff")
    w.cv_curveGraph.configure(highlightcolor="black")
    w.cv_curveGraph.configure(insertbackground="black")
    w.cv_curveGraph.configure(relief='ridge')
    w.cv_curveGraph.configure(selectbackground="#c4c4c4")
    w.cv_curveGraph.configure(selectforeground="black")
    w.cv_curveGraph.configure(width=823)

    w.fr_toolbar = tk.Frame(w.fr_mainView)
    w.fr_toolbar.place(relx=0.012, rely=0.02, height=38, relwidth=0.974)
    w.fr_toolbar.configure(relief='groove')
    w.fr_toolbar.configure(borderwidth="2")
    w.fr_toolbar.configure(relief='groove')
    w.fr_toolbar.configure(background="#f9f9f9")
    w.fr_toolbar.configure(highlightbackground="#f9f9f9")
    w.fr_toolbar.configure(highlightcolor="black")
    w.fr_toolbar.configure(width=823)    

def btn_import(p1):
    global curvesList, curvePlot, spAt, cnvAt
    curvePlot = np.ndarray([])
    curvesList = np.ndarray([])
    
    imp = filedialog.askopenfilename(initialdir = "C:/", title = "Importar CSV...",
                                     filetypes = (("Comma-separeted values", "*.csv"),
                                                  ("All files", "*.*")))
    if imp:
        csv = ctrl.file.importCsv(imp)
        top_level.title("VStat - " + csv.curveName + ".csv")
        
        curvePlot = np.append(curvePlot, csv, axis=None)
        
        spAt, cnvAt = drawCurve()
        cnvAt.draw()
        
        curvesList = np.append(curvesList, csv, axis=None)

        createMins()
        
def btn_export(p1):
    global curvePlot
    
    if curvePlot.size == 2:
        
        csvName = filedialog.asksaveasfilename(title='Exportar CSV...', defaultextension = 'csv', initialdir = "C:/", filetypes = (("Comma-separeted values", "*.csv"), ("All files", "*.*")))
        
        ctrl.file.exportCsv(np.take(curvePlot, 1), csvName)
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nexportar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Sem curva para\nexportar")
    
        
def btn_connect(p1):
    global conn
    
    if conn:
        ctrl.connection.disconnect()
        conn = 0
        w.btn_connect.configure(text='''Conectar''', background="#738c8c")
        w.btn_connect.update()
        w.lb_ConnInfo.configure(text="VStat desconectado")
    else:
        vstat = ctrl.connection.connect()
        if vstat:
            conn = 1
            w.lb_ConnInfo.configure(text="VStat conectado\nPorta "+vstat)
            w.btn_connect.configure(text='''Desconectar''', background="#00cccc")
            w.btn_connect.update()
        else:
            w.lb_ConnInfo.configure(text="VStat não encontrado")
            
def btn_iniciar(p1):
    global curvePlot, curvesList, spAt, cnvAt, md_dpv
    
    md_dpv.pIni = w.et_PInicio.get()
    md_dpv.pFim = w.et_PFim.get()
    md_dpv.pPul = w.et_PPulso.get()
    md_dpv.pPas = w.et_PPasso.get()
    md_dpv.tPul = w.et_TPulso.get()
    md_dpv.tPas = w.et_tPasso.get()
    md_dpv.tEqu = w.et_tEquil.get()
    md_dpv.fEsc = w.cb_intCorrente.current()
    
    # Limpa o frame de miniaturas
    destroyChildren(w.fr_miniaturas)
    w.fr_miniaturas.update()
    
    # Verifica se o potenciostato está conectado e inicia a análise
    ini = ctrl.connection.openPort()
    if ini:
        w.lb_ConnInfo.configure(text="VStat não conectado")
        w.btn_connect.configure(background="#ff6666")
        w.btn_connect.update()
    else:
        
        """x = np.arange(float(w.et_PInicio.get()), float(w.et_PFim.get()), float(w.et_PPasso.get()))
        y = np.arange(0, x.size, 1)
        c = md.curve("live Plot", x, y)
        curvePlot = np.append(curvePlot, c)"""
        ctrl.transmition.transmit(str(w.cb_intCorrente.current()),
                                  w.et_PInicio.get(),
                                  w.et_PFim.get(),
                                  w.et_PPulso.get(),
                                  w.et_PPasso.get(),
                                  w.et_TPulso.get(),
                                  w.et_tPasso.get(),
                                  w.et_tEquil.get())
        
        destroyChildren(w.fr_mainView)
        
        # Fundo de escala
        
        if w.cb_intCorrente.current() == 0:
            fe = 5/(4096/3.3)
            print("Escala: Automática")
            print("fundo de escala(inicial): ", fe)
        else:
            fe = int(w.cb_intCorrente.get()[4:-2])/(4096/3.3)
            print("Escala: ", w.cb_intCorrente.get()[4:-2])
            print("fundo de escala: ", fe)
        
        curvePlot = np.ndarray([])
        curvePlot = np.append(curvePlot, md.curve("", np.array([]), np.array([])))
        spAt, cnvAt = drawCurve()
        
        curvesList = ctrl.transmition.receive(curvePlot, spAt, cnvAt, fe, float(w.et_PInicio.get()), float(w.et_PPasso.get()))#, canvas)
        #curvePlot = np.append(curvePlot, np.take(curvesList, 1))
        
        
        ctrl.connection.closePort()
        #if dpv:
        
        top_level.title("VStat - " + np.take(curvePlot, 1).curveName)#dpv.curveName)
            
        #createCanvas()
            
        #spAt, cnvAt = drawCurve()
        
        createMins()

def drawCurve():
    global curvePlot, sp, fig

    createCanvas()
    fig = Figure(figsize=(10, 8), dpi = 100)
    sp = fig.add_subplot(111, xlabel="Potencial em Volts (V)", ylabel="Corrente em Microampere (µA)")#, title=cv.curveName)
    canvas = FigureCanvasTkAgg(fig, master = w.cv_curveGraph)
    toolbar = NavigationToolbar2Tk(canvas, w.fr_toolbar)
    
    if curvePlot.size == 2:
        cv = np.take(curvePlot, 1)
        
        sp.set_title(cv.curveName)
        
        sp.plot(cv.curveX, cv.curveY, color=cv.color)

    elif curvePlot.size > 2:
        sp.set_title("untitle merge")
        for i in range(1, curvePlot.size):
            cv = np.take(curvePlot, i)
            sp.plot(cv.curveX, cv.curveY, color=cv.color)
            
            
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
    #canvas.draw()
    canvas.get_tk_widget().pack(side = tk.TOP, fill = tk.BOTH, expand = 1)
    
    return sp, canvas
    
def expandMin(curveIndex):
    global curvesList, curvePlot, spAt, cnvAt
    cv = np.take(curvesList, curveIndex+1)
    curvePlot = np.ndarray([])
    curvePlot = np.append(curvePlot, cv, axis=None) 
    spAt, cnvAt = drawCurve()
    
def createMins():
    global cBoxList, curvesList, qtdMin
    
    # Apaga miniaturas existentes
    qtdMin = 0
    destroyChildren(w.fr_miniaturas)
    
    # Cria miniaturas para cada curva na lista
    for i in range(1, curvesList.size):
        curve = np.take(curvesList, i)
        createMin(curve)

def createMin(curve):
    global qtdMin, cBoxList
    
    cBoxList = np.append(cBoxList, IntVar(), axis=None)
    
    thisIndex = qtdMin
    
    relX = 0.01
    
    if qtdMin == 0:
        qtdMin += 1
    elif qtdMin > 0:
        relX = (0.152 * qtdMin) + 0.01
        qtdMin += 1
    
    # Titulo superior das miniaturas
    w.lb_minCurve = tk.Label(w.fr_miniaturas)
    w.lb_minCurve.place(relx=relX, rely=0.058, height=21, width=133)
    w.lb_minCurve.configure(background="#d9d9d9")
    w.lb_minCurve.configure(disabledforeground="#a3a3a3")
    w.lb_minCurve.configure(foreground="#000000")
    w.lb_minCurve.configure(text=curve.curveName)
    w.lb_minCurve.configure(width=133)
    w.lb_minCurve.bind("<Button-1>", lambda x:expandMin(thisIndex))
    
    # Canvas para desenhar a miniatura
    w.cv_minCurve = tk.Canvas(w.fr_miniaturas)
    w.cv_minCurve.place(relx=relX, rely=0.165, height=112, width=133)
    
    fig = Figure(figsize=(1, 1), dpi = 100)
    canvas = FigureCanvasTkAgg(fig, master = w.cv_minCurve)
    #toolbar = NavigationToolbar2Tk(canvas, w.fr_toolbar)
            
    sp = fig.add_subplot(111)
    
    sp.plot(curve.curveX, curve.curveY)
            
    #toolbar.update()
    #canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    canvas.mpl_connect('button_press_event', lambda x: expandMin(thisIndex))
    
    w.cb_chooser = tk.Checkbutton(w.cv_minCurve)
    w.cb_chooser.place(relx=0.075, rely=0.097, relheight=0.243, relwidth=0.211)
    w.cb_chooser.configure(activebackground="#ececec")
    w.cb_chooser.configure(activeforeground="#000000")
    w.cb_chooser.configure(background="#d9d9d9")
    w.cb_chooser.configure(disabledforeground="#a3a3a3")
    w.cb_chooser.configure(foreground="#000000")
    w.cb_chooser.configure(highlightbackground="#d9d9d9")
    w.cb_chooser.configure(highlightcolor="black")
    w.cb_chooser.configure(justify='left')
    w.cb_chooser.configure(variable=np.take(cBoxList, thisIndex+1))

    w.fr_color = tk.Frame(w.cv_minCurve)
    w.fr_color.place(relx=0.752, rely=0.097, relheight=0.243, relwidth=0.188)
    w.fr_color.configure(relief='groove')
    w.fr_color.configure(borderwidth="2")
    w.fr_color.configure(relief='groove')
    w.fr_color.configure(background="#1559c6")
    w.fr_color.configure(width=25)
    w.fr_color.bind("<Button-1>", lambda e:changeColor(e, thisIndex, sp, canvas))

def destroyChildren(frame):
    for child in frame.winfo_children():
        if child.winfo_children():
            destroyChildren(child)

        child.destroy()

def changeColor(p1, curveIndex, sp, canvas):
    global curvesList, curvePlot
    color = colorchooser.askcolor()
    c = str(color)
    c = c[-9:-2]
    cv = np.take(curvesList, curveIndex+1)
    cv.color = c
    sp.plot(cv.curveX, cv.curveY, c)
    canvas.draw()
    p1.widget.configure(background=cv.color)
    p1.widget.update()
    drawCurve()
    
def curvesJoin():
    global curvePlot
    count = 0
    for i in range(1, cBoxList.size):
        c = np.take(cBoxList, i)
        if c.get():
            if count < 1:
                cv = np.take(curvesList, i)
                curvePlot = np.ndarray([])
                curvePlot = np.append(curvePlot, cv, axis=None)
                count += 1
            else:
                cv = np.take(curvesList, i)
                curvePlot = np.append(curvePlot, cv, axis=None)
                count += 1
        c.set(0)
    if count <= 1:
        w.lb_ConnInfo.configure(text="Selecione ao menos\nduas curvas")
    else:
        drawCurve()
        
def removeCurve():
    global curvesList, cBoxList, curvePlot
    #print("remover")
    i = 1
    while i < cBoxList.size:
        c = np.take(cBoxList, i)
        t = np.take(curvesList, i)
        p = np.take(curvePlot, 1)
        if t is p:
            #print("Igual")
            pass
        #print("c: "+ str(c.get()))
        if c.get():
            #if t is p:
                
            curvesList = np.delete(curvesList, i)
            cBoxList = np.delete(cBoxList, i)
        else:
            i += 1
    createMins() 

#-----------------------------------------------------#
#                      PAINEIS                        #
#-----------------------------------------------------#
   
#---- Painel DPV ----#
def painelDPV():
    global md_dpv
    destroyChildren(w.fr_analise)
    w.fr_analise.configure(text='''DPV''')
    
    vcmd = w.fr_analise.register(validation.entryValidate)
    
    # Inicializa entradas que serão manipuladas
    w.et_PInicio = tk.Entry(w.fr_analise)
    w.et_PFim = tk.Entry(w.fr_analise)
    w.et_PPasso = tk.Entry(w.fr_analise)
    w.et_tPasso = tk.Entry(w.fr_analise)
    
    w.lb_PInicio = tk.Label(w.fr_analise, anchor="w")
    w.lb_PInicio.place(relx=0.053, y=17, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PInicio)
    w.lb_PInicio.configure(text='''Pot. Inicial (V)''')
    
    w.et_PInicio.configure(validate="key")
    w.et_PInicio.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_PInicio.place(relx=0.59, y=18, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PInicio)
    ctrl.validation.entryInsert(w.et_PInicio, md_dpv.pIni)

    w.lb_PFim = tk.Label(w.fr_analise, anchor="w")
    w.lb_PFim.place(relx=0.053, y=43, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PFim)
    w.lb_PFim.configure(text='''Pot. Final (V)''')
    w.lb_PFim.configure(width=71)

    w.et_PFim.configure(validate="key")
    w.et_PFim.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PFim.place(relx=0.59, y=44, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PFim)
    ctrl.validation.entryInsert(w.et_PFim, md_dpv.pFim)

    w.lb_PPasso = tk.Label(w.fr_analise, anchor="w")
    w.lb_PPasso.place(relx=0.053, y=69, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PPasso)
    w.lb_PPasso.configure(text='''Pot. Passo (V)''')
    w.lb_PPasso.configure(width=81)
    
    w.et_PPasso.configure(validate="key")
    w.et_PPasso.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PPasso.place(relx=0.59, y=70, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PPasso)
    ctrl.validation.entryInsert(w.et_PPasso, md_dpv.pPas)

    w.lb_PPulso = tk.Label(w.fr_analise, anchor="w")
    w.lb_PPulso.place(relx=0.053, y=95, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PPulso)
    w.lb_PPulso.configure(text='''Pot. Pulso (V)''')

    w.et_PPulso = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PPulso.place(relx=0.59, y=96, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PPulso)
    ctrl.validation.entryInsert(w.et_PPulso, md_dpv.pPul)    

    w.lb_TPulso = tk.Label(w.fr_analise, anchor="w")
    w.lb_TPulso.place(relx=0.053, y=121, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_TPulso)
    w.lb_TPulso.configure(text='''Tem. Pulso (s)''')
    w.lb_TPulso.configure(width=91)

    w.et_TPulso = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_TPulso.place(relx=0.59, y=122, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_TPulso)
    ctrl.validation.entryInsert(w.et_TPulso, md_dpv.tPul)

    w.lb_tPasso = tk.Label(w.fr_analise, anchor="w")
    w.lb_tPasso.place(relx=0.053, y=147, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_tPasso)
    w.lb_tPasso.configure(text='''Tem. Passo (s)''')
    
    w.et_tPasso.configure(validate="key")
    w.et_tPasso.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_tPasso.place(relx=0.59, y=148, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_tPasso)
    ctrl.validation.entryInsert(w.et_tPasso, md_dpv.tPas)
    
    w.lb_tEquil = tk.Label(w.fr_analise, anchor="w")
    w.lb_tEquil.place(relx=0.053, y=173, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_tEquil)
    w.lb_tEquil.configure(text='''Tem. equilíbrio (s)''')

    w.et_tEquil = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_tEquil.place(relx=0.59, y=174, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_tEquil)
    ctrl.validation.entryInsert(w.et_tEquil, md_dpv.tEqu)
    
    w.lb_currentRange = tk.Label(w.fr_analise, anchor="w")
    w.lb_currentRange.place(relx=0.053, y=199, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_currentRange)
    w.lb_currentRange.configure(text='''Int. Corrente''')
    
    w.cb_intCorrente = ttk.Combobox(w.fr_analise)
    w.cb_intCorrente.place(relx=0.59, y=183, height=20, width=77)
    w.cb_intCorrente.configure(values=["auto","+/- 5uA","+/- 10uA","+/- 20uA", "+/- 50uA"])
    w.cb_intCorrente.current(md_dpv.fEsc)
    
    w.lb_sRate = tk.Label(w.fr_analise, anchor="w")
    w.lb_sRate.place(relx=0.053, y=225, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_sRate)
    w.lb_sRate.configure(text='''SRate (V/s)''')

    w.et_sRate = tk.Entry(w.fr_analise, state="disabled")
    w.et_sRate.place(relx=0.59, y=226, height=20, width=77
            , bordermode='ignore')
    
    w.lb_tEstimado = tk.Label(w.fr_analise, anchor="w")
    w.lb_tEstimado.place(relx=0.053, y=251, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_tEstimado)
    w.lb_tEstimado.configure(text='''Tem. Estimado (s)''')

    w.et_tEstimado = tk.Entry(w.fr_analise, state="disabled")
    w.et_tEstimado.place(relx=0.59, y=252, height=20, width=77
            , bordermode='ignore')
    
    w.lb_nPontos = tk.Label(w.fr_analise, anchor="w")
    w.lb_nPontos.place(relx=0.053, y=277, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_nPontos)
    w.lb_nPontos.configure(text='''Nº Pontos''')

    w.et_nPontos = tk.Entry(w.fr_analise, state="disabled")
    w.et_nPontos.place(relx=0.59, y=278, height=20, width=77
            , bordermode='ignore')
    
    w.btn_dpv = tk.Button(w.fr_analise)
    w.btn_dpv.place(relx=0.063, y=315, height=24, relwidth=0.88
            , bordermode='ignore')
    es.btnStyle(w.btn_dpv)
    w.btn_dpv.configure(text='''Iniciar''')
    w.btn_dpv.configure(width=167)
    w.btn_dpv.bind('<ButtonRelease-1>',lambda e:btn_iniciar(e))
    
    validation.updateInfo(float(w.et_PInicio.get()), float(w.et_PFim.get()), float(w.et_PPasso.get()), float(w.et_tPasso.get()))
    
#---- Operações de tratamento da curva ----#
    
def op_frame2param(frName, p1Name, p1Value, p2Name, p2Value, callback):
    destroyChildren(w.fr_analise)
    w.fr_analise.configure(text=frName)
    
    vcmd = w.fr_analise.register(validation.entryValidate)
    
    w.lb_Param1 = tk.Label(w.fr_analise, anchor="w")
    w.lb_Param1.place(relx=0.053, y=17, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_Param1)
    w.lb_Param1.configure(text=p1Name)

    w.et_Param1 = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_Param1.place(relx=0.59, y=18, height=20, width=74
            , bordermode='ignore')
    es.etStyle(w.et_Param1)
    w.et_Param1.configure(width=74)
    ctrl.validation.entryInsert(w.et_Param1, p1Value)

    
    w.lb_Param2 = tk.Label(w.fr_analise, anchor="w")
    w.lb_Param2.place(relx=0.053, y=43, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_Param2)
    w.lb_Param2.configure(text=p2Name)

    w.et_Param2 = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_Param2.place(relx=0.59, y=44, height=20, width=74
            , bordermode='ignore')
    es.etStyle(w.et_Param2)
    ctrl.validation.entryInsert(w.et_Param2, p2Value)
    
    w.btn_Apply = tk.Button(w.fr_analise)
    w.btn_Apply.place(relx=0.063, y=315, height=24, relwidth=0.88
            , bordermode='ignore')
    es.btnStyle(w.btn_Apply)
    w.btn_Apply.configure(text='''Aplicar''')
    w.btn_Apply.configure(width=167)
    w.btn_Apply.bind('<ButtonRelease-1>',lambda x:aplicar(callback, (w.et_Param1.get(), w.et_Param2.get())))
    
def fd_PEAK():
    global curvePlot, spAt, cnvAt
    
    if curvePlot.size == 2:
        cv = np.take(curvePlot, 1)
        i = ctrl.operations.findPeak(cv.curveY)
        spAt.scatter(cv.curveX[i],cv.curveY[i])
        cnvAt.draw()
        w.lb_ConnInfo.configure(text="PICO\nPotencial = "+str(float("{0:.4f}".format(cv.curveX[i])))+"V\nCorrente = "+str(float("{0:.3f}".format(cv.curveY[i])))+"uA")
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nanalisar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Selecione uma curva")

def aplicar(callback, args):
    global curvePlot, curvesList
    
    if curvePlot.size == 2:
        c = np.take(curvePlot, 1)
        y = callback(c.curveY, *args)
        c2 = md.curve(c.curveName+"_"+callback.__name__, c.curveX, y)
        c2.curveX = c.curveX
        c2.curveY = y
        
        curvePlot = np.ndarray([])
        curvePlot = np.append(curvePlot, c2, axis=None)
        drawCurve()
        
        curvesList = np.append(curvesList, c2, axis=None)
        createMins()
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nanalisar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Selecione uma curva")
    
""" apagar filhos de um frame

    for child in infoFrame.winfo_children():
    child.destroy()
    
"""
#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.20
#  in conjunction with Tcl version 8.6
#    Feb 18, 2019 11:55:48 AM -03  platform: Windows NT
#    Feb 19, 2019 09:09:42 AM -03  platform: Windows NT
"""
Created on Mon Feb 18 10:08:04 2019

@author: <NAME>
"""
import sys

import Controller as ctrl
import Model as md
import Estilos as es

import numpy as np
#from numpy import array, concatenate, ndarray, append, take, delete


import pandas as pd

from tkinter import filedialog, colorchooser, IntVar

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True 

def set_var():
    global conn, qtdMin, curvePlot, curvesList, cBoxList, md_dpv, validation
    conn = 0
    qtdMin = 0
    curvePlot = np.ndarray([])
    curvesList = np.ndarray([])
    cBoxList = np.ndarray([])
    md_dpv = md.dpv()
    validation = ctrl.validation(w, root)
    

def init(top, gui, *args, **kwargs):
    global w, top_level, root, font9
    w = gui
    top_level = top
    root = top
    #font9 = "-family {Segoe UI} -size 9 -weight bold -slant roman "  \
    #        "-underline 0 -overstrike 0"
    set_var()
    painelDPV()

def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None

if __name__ == '__main__':
    import VStat
    VStat.vp_start_gui()
    
##########  Funções ###########
def createCanvas():
    w.cv_curveGraph = tk.Canvas(w.fr_mainView)
    w.cv_curveGraph.place(relx=0.012, rely=0.119, relheight=0.857, relwidth=0.974)
    w.cv_curveGraph.configure(background="#ffffff")
    w.cv_curveGraph.configure(highlightbackground="#ffffff")
    w.cv_curveGraph.configure(highlightcolor="black")
    w.cv_curveGraph.configure(insertbackground="black")
    w.cv_curveGraph.configure(relief='ridge')
    w.cv_curveGraph.configure(selectbackground="#c4c4c4")
    w.cv_curveGraph.configure(selectforeground="black")
    w.cv_curveGraph.configure(width=823)

    w.fr_toolbar = tk.Frame(w.fr_mainView)
    w.fr_toolbar.place(relx=0.012, rely=0.02, height=38, relwidth=0.974)
    w.fr_toolbar.configure(relief='groove')
    w.fr_toolbar.configure(borderwidth="2")
    w.fr_toolbar.configure(relief='groove')
    w.fr_toolbar.configure(background="#f9f9f9")
    w.fr_toolbar.configure(highlightbackground="#f9f9f9")
    w.fr_toolbar.configure(highlightcolor="black")
    w.fr_toolbar.configure(width=823)    

def btn_import(p1):
    global curvesList, curvePlot, spAt, cnvAt
    curvePlot = np.ndarray([])
    curvesList = np.ndarray([])
    
    imp = filedialog.askopenfilename(initialdir = "C:/", title = "Importar CSV...",
                                     filetypes = (("Comma-separeted values", "*.csv"),
                                                  ("All files", "*.*")))
    if imp:
        csv = ctrl.file.importCsv(imp)
        top_level.title("VStat - " + csv.curveName + ".csv")
        
        curvePlot = np.append(curvePlot, csv, axis=None)
        
        spAt, cnvAt = drawCurve()
        cnvAt.draw()
        
        curvesList = np.append(curvesList, csv, axis=None)

        createMins()
        
def btn_export(p1):
    global curvePlot
    
    if curvePlot.size == 2:
        
        csvName = filedialog.asksaveasfilename(title='Exportar CSV...', defaultextension = 'csv', initialdir = "C:/", filetypes = (("Comma-separeted values", "*.csv"), ("All files", "*.*")))
        
        ctrl.file.exportCsv(np.take(curvePlot, 1), csvName)
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nexportar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Sem curva para\nexportar")
    
        
def btn_connect(p1):
    global conn
    
    if conn:
        ctrl.connection.disconnect()
        conn = 0
        w.btn_connect.configure(text='''Conectar''', background="#738c8c")
        w.btn_connect.update()
        w.lb_ConnInfo.configure(text="VStat desconectado")
    else:
        vstat = ctrl.connection.connect()
        if vstat:
            conn = 1
            w.lb_ConnInfo.configure(text="VStat conectado\nPorta "+vstat)
            w.btn_connect.configure(text='''Desconectar''', background="#00cccc")
            w.btn_connect.update()
        else:
            w.lb_ConnInfo.configure(text="VStat não encontrado")
            
def btn_iniciar(p1):
    global curvePlot, curvesList, spAt, cnvAt, md_dpv
    
    md_dpv.pIni = w.et_PInicio.get()
    md_dpv.pFim = w.et_PFim.get()
    md_dpv.pPul = w.et_PPulso.get()
    md_dpv.pPas = w.et_PPasso.get()
    md_dpv.tPul = w.et_TPulso.get()
    md_dpv.tPas = w.et_tPasso.get()
    md_dpv.tEqu = w.et_tEquil.get()
    md_dpv.fEsc = w.cb_intCorrente.current()
    
    # Limpa o frame de miniaturas
    destroyChildren(w.fr_miniaturas)
    w.fr_miniaturas.update()
    
    # Verifica se o potenciostato está conectado e inicia a análise
    ini = ctrl.connection.openPort()
    if ini:
        w.lb_ConnInfo.configure(text="VStat não conectado")
        w.btn_connect.configure(background="#ff6666")
        w.btn_connect.update()
    else:
        
        """x = np.arange(float(w.et_PInicio.get()), float(w.et_PFim.get()), float(w.et_PPasso.get()))
        y = np.arange(0, x.size, 1)
        c = md.curve("live Plot", x, y)
        curvePlot = np.append(curvePlot, c)"""
        ctrl.transmition.transmit(str(w.cb_intCorrente.current()),
                                  w.et_PInicio.get(),
                                  w.et_PFim.get(),
                                  w.et_PPulso.get(),
                                  w.et_PPasso.get(),
                                  w.et_TPulso.get(),
                                  w.et_tPasso.get(),
                                  w.et_tEquil.get())
        
        destroyChildren(w.fr_mainView)
        
        # Fundo de escala
        
        if w.cb_intCorrente.current() == 0:
            fe = 5/(4096/3.3)
            print("Escala: Automática")
            print("fundo de escala(inicial): ", fe)
        else:
            fe = int(w.cb_intCorrente.get()[4:-2])/(4096/3.3)
            print("Escala: ", w.cb_intCorrente.get()[4:-2])
            print("fundo de escala: ", fe)
        
        curvePlot = np.ndarray([])
        curvePlot = np.append(curvePlot, md.curve("", np.array([]), np.array([])))
        spAt, cnvAt = drawCurve()
        
        curvesList = ctrl.transmition.receive(curvePlot, spAt, cnvAt, fe, float(w.et_PInicio.get()), float(w.et_PPasso.get()))#, canvas)
        #curvePlot = np.append(curvePlot, np.take(curvesList, 1))
        
        
        ctrl.connection.closePort()
        #if dpv:
        
        top_level.title("VStat - " + np.take(curvePlot, 1).curveName)#dpv.curveName)
            
        #createCanvas()
            
        #spAt, cnvAt = drawCurve()
        
        createMins()

def drawCurve():
    global curvePlot, sp, fig

    createCanvas()
    fig = Figure(figsize=(10, 8), dpi = 100)
    sp = fig.add_subplot(111, xlabel="Potencial em Volts (V)", ylabel="Corrente em Microampere (µA)")#, title=cv.curveName)
    canvas = FigureCanvasTkAgg(fig, master = w.cv_curveGraph)
    toolbar = NavigationToolbar2Tk(canvas, w.fr_toolbar)
    
    if curvePlot.size == 2:
        cv = np.take(curvePlot, 1)
        
        sp.set_title(cv.curveName)
        
        sp.plot(cv.curveX, cv.curveY, color=cv.color)

    elif curvePlot.size > 2:
        sp.set_title("untitle merge")
        for i in range(1, curvePlot.size):
            cv = np.take(curvePlot, i)
            sp.plot(cv.curveX, cv.curveY, color=cv.color)
            
            
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
    #canvas.draw()
    canvas.get_tk_widget().pack(side = tk.TOP, fill = tk.BOTH, expand = 1)
    
    return sp, canvas
    
def expandMin(curveIndex):
    global curvesList, curvePlot, spAt, cnvAt
    cv = np.take(curvesList, curveIndex+1)
    curvePlot = np.ndarray([])
    curvePlot = np.append(curvePlot, cv, axis=None) 
    spAt, cnvAt = drawCurve()
    
def createMins():
    global cBoxList, curvesList, qtdMin
    
    # Apaga miniaturas existentes
    qtdMin = 0
    destroyChildren(w.fr_miniaturas)
    
    # Cria miniaturas para cada curva na lista
    for i in range(1, curvesList.size):
        curve = np.take(curvesList, i)
        createMin(curve)

def createMin(curve):
    global qtdMin, cBoxList
    
    cBoxList = np.append(cBoxList, IntVar(), axis=None)
    
    thisIndex = qtdMin
    
    relX = 0.01
    
    if qtdMin == 0:
        qtdMin += 1
    elif qtdMin > 0:
        relX = (0.152 * qtdMin) + 0.01
        qtdMin += 1
    
    # Titulo superior das miniaturas
    w.lb_minCurve = tk.Label(w.fr_miniaturas)
    w.lb_minCurve.place(relx=relX, rely=0.058, height=21, width=133)
    w.lb_minCurve.configure(background="#d9d9d9")
    w.lb_minCurve.configure(disabledforeground="#a3a3a3")
    w.lb_minCurve.configure(foreground="#000000")
    w.lb_minCurve.configure(text=curve.curveName)
    w.lb_minCurve.configure(width=133)
    w.lb_minCurve.bind("<Button-1>", lambda x:expandMin(thisIndex))
    
    # Canvas para desenhar a miniatura
    w.cv_minCurve = tk.Canvas(w.fr_miniaturas)
    w.cv_minCurve.place(relx=relX, rely=0.165, height=112, width=133)
    
    fig = Figure(figsize=(1, 1), dpi = 100)
    canvas = FigureCanvasTkAgg(fig, master = w.cv_minCurve)
    #toolbar = NavigationToolbar2Tk(canvas, w.fr_toolbar)
            
    sp = fig.add_subplot(111)
    
    sp.plot(curve.curveX, curve.curveY)
            
    #toolbar.update()
    #canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    canvas.mpl_connect('button_press_event', lambda x: expandMin(thisIndex))
    
    w.cb_chooser = tk.Checkbutton(w.cv_minCurve)
    w.cb_chooser.place(relx=0.075, rely=0.097, relheight=0.243, relwidth=0.211)
    w.cb_chooser.configure(activebackground="#ececec")
    w.cb_chooser.configure(activeforeground="#000000")
    w.cb_chooser.configure(background="#d9d9d9")
    w.cb_chooser.configure(disabledforeground="#a3a3a3")
    w.cb_chooser.configure(foreground="#000000")
    w.cb_chooser.configure(highlightbackground="#d9d9d9")
    w.cb_chooser.configure(highlightcolor="black")
    w.cb_chooser.configure(justify='left')
    w.cb_chooser.configure(variable=np.take(cBoxList, thisIndex+1))

    w.fr_color = tk.Frame(w.cv_minCurve)
    w.fr_color.place(relx=0.752, rely=0.097, relheight=0.243, relwidth=0.188)
    w.fr_color.configure(relief='groove')
    w.fr_color.configure(borderwidth="2")
    w.fr_color.configure(relief='groove')
    w.fr_color.configure(background="#1559c6")
    w.fr_color.configure(width=25)
    w.fr_color.bind("<Button-1>", lambda e:changeColor(e, thisIndex, sp, canvas))

def destroyChildren(frame):
    for child in frame.winfo_children():
        if child.winfo_children():
            destroyChildren(child)

        child.destroy()

def changeColor(p1, curveIndex, sp, canvas):
    global curvesList, curvePlot
    color = colorchooser.askcolor()
    c = str(color)
    c = c[-9:-2]
    cv = np.take(curvesList, curveIndex+1)
    cv.color = c
    sp.plot(cv.curveX, cv.curveY, c)
    canvas.draw()
    p1.widget.configure(background=cv.color)
    p1.widget.update()
    drawCurve()
    
def curvesJoin():
    global curvePlot
    count = 0
    for i in range(1, cBoxList.size):
        c = np.take(cBoxList, i)
        if c.get():
            if count < 1:
                cv = np.take(curvesList, i)
                curvePlot = np.ndarray([])
                curvePlot = np.append(curvePlot, cv, axis=None)
                count += 1
            else:
                cv = np.take(curvesList, i)
                curvePlot = np.append(curvePlot, cv, axis=None)
                count += 1
        c.set(0)
    if count <= 1:
        w.lb_ConnInfo.configure(text="Selecione ao menos\nduas curvas")
    else:
        drawCurve()
        
def removeCurve():
    global curvesList, cBoxList, curvePlot
    #print("remover")
    i = 1
    while i < cBoxList.size:
        c = np.take(cBoxList, i)
        t = np.take(curvesList, i)
        p = np.take(curvePlot, 1)
        if t is p:
            #print("Igual")
            pass
        #print("c: "+ str(c.get()))
        if c.get():
            #if t is p:
                
            curvesList = np.delete(curvesList, i)
            cBoxList = np.delete(cBoxList, i)
        else:
            i += 1
    createMins() 

#-----------------------------------------------------#
#                      PAINEIS                        #
#-----------------------------------------------------#
   
#---- Painel DPV ----#
def painelDPV():
    global md_dpv
    destroyChildren(w.fr_analise)
    w.fr_analise.configure(text='''DPV''')
    
    vcmd = w.fr_analise.register(validation.entryValidate)
    
    # Inicializa entradas que serão manipuladas
    w.et_PInicio = tk.Entry(w.fr_analise)
    w.et_PFim = tk.Entry(w.fr_analise)
    w.et_PPasso = tk.Entry(w.fr_analise)
    w.et_tPasso = tk.Entry(w.fr_analise)
    
    w.lb_PInicio = tk.Label(w.fr_analise, anchor="w")
    w.lb_PInicio.place(relx=0.053, y=17, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PInicio)
    w.lb_PInicio.configure(text='''Pot. Inicial (V)''')
    
    w.et_PInicio.configure(validate="key")
    w.et_PInicio.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_PInicio.place(relx=0.59, y=18, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PInicio)
    ctrl.validation.entryInsert(w.et_PInicio, md_dpv.pIni)

    w.lb_PFim = tk.Label(w.fr_analise, anchor="w")
    w.lb_PFim.place(relx=0.053, y=43, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PFim)
    w.lb_PFim.configure(text='''Pot. Final (V)''')
    w.lb_PFim.configure(width=71)

    w.et_PFim.configure(validate="key")
    w.et_PFim.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PFim.place(relx=0.59, y=44, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PFim)
    ctrl.validation.entryInsert(w.et_PFim, md_dpv.pFim)

    w.lb_PPasso = tk.Label(w.fr_analise, anchor="w")
    w.lb_PPasso.place(relx=0.053, y=69, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PPasso)
    w.lb_PPasso.configure(text='''Pot. Passo (V)''')
    w.lb_PPasso.configure(width=81)
    
    w.et_PPasso.configure(validate="key")
    w.et_PPasso.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PPasso.place(relx=0.59, y=70, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PPasso)
    ctrl.validation.entryInsert(w.et_PPasso, md_dpv.pPas)

    w.lb_PPulso = tk.Label(w.fr_analise, anchor="w")
    w.lb_PPulso.place(relx=0.053, y=95, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_PPulso)
    w.lb_PPulso.configure(text='''Pot. Pulso (V)''')

    w.et_PPulso = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    
    w.et_PPulso.place(relx=0.59, y=96, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_PPulso)
    ctrl.validation.entryInsert(w.et_PPulso, md_dpv.pPul)    

    w.lb_TPulso = tk.Label(w.fr_analise, anchor="w")
    w.lb_TPulso.place(relx=0.053, y=121, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_TPulso)
    w.lb_TPulso.configure(text='''Tem. Pulso (s)''')
    w.lb_TPulso.configure(width=91)

    w.et_TPulso = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_TPulso.place(relx=0.59, y=122, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_TPulso)
    ctrl.validation.entryInsert(w.et_TPulso, md_dpv.tPul)

    w.lb_tPasso = tk.Label(w.fr_analise, anchor="w")
    w.lb_tPasso.place(relx=0.053, y=147, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_tPasso)
    w.lb_tPasso.configure(text='''Tem. Passo (s)''')
    
    w.et_tPasso.configure(validate="key")
    w.et_tPasso.configure(validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_tPasso.place(relx=0.59, y=148, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_tPasso)
    ctrl.validation.entryInsert(w.et_tPasso, md_dpv.tPas)
    
    w.lb_tEquil = tk.Label(w.fr_analise, anchor="w")
    w.lb_tEquil.place(relx=0.053, y=173, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_tEquil)
    w.lb_tEquil.configure(text='''Tem. equilíbrio (s)''')

    w.et_tEquil = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_tEquil.place(relx=0.59, y=174, height=20, width=77
            , bordermode='ignore')
    es.etStyle(w.et_tEquil)
    ctrl.validation.entryInsert(w.et_tEquil, md_dpv.tEqu)
    
    w.lb_currentRange = tk.Label(w.fr_analise, anchor="w")
    w.lb_currentRange.place(relx=0.053, y=199, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_currentRange)
    w.lb_currentRange.configure(text='''Int. Corrente''')
    
    w.cb_intCorrente = ttk.Combobox(w.fr_analise)
    w.cb_intCorrente.place(relx=0.59, y=183, height=20, width=77)
    w.cb_intCorrente.configure(values=["auto","+/- 5uA","+/- 10uA","+/- 20uA", "+/- 50uA"])
    w.cb_intCorrente.current(md_dpv.fEsc)
    
    w.lb_sRate = tk.Label(w.fr_analise, anchor="w")
    w.lb_sRate.place(relx=0.053, y=225, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_sRate)
    w.lb_sRate.configure(text='''SRate (V/s)''')

    w.et_sRate = tk.Entry(w.fr_analise, state="disabled")
    w.et_sRate.place(relx=0.59, y=226, height=20, width=77
            , bordermode='ignore')
    
    w.lb_tEstimado = tk.Label(w.fr_analise, anchor="w")
    w.lb_tEstimado.place(relx=0.053, y=251, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_tEstimado)
    w.lb_tEstimado.configure(text='''Tem. Estimado (s)''')

    w.et_tEstimado = tk.Entry(w.fr_analise, state="disabled")
    w.et_tEstimado.place(relx=0.59, y=252, height=20, width=77
            , bordermode='ignore')
    
    w.lb_nPontos = tk.Label(w.fr_analise, anchor="w")
    w.lb_nPontos.place(relx=0.053, y=277, height=21, width=110
            , bordermode='ignore')
    es.lbStyle(w.lb_nPontos)
    w.lb_nPontos.configure(text='''Nº Pontos''')

    w.et_nPontos = tk.Entry(w.fr_analise, state="disabled")
    w.et_nPontos.place(relx=0.59, y=278, height=20, width=77
            , bordermode='ignore')
    
    w.btn_dpv = tk.Button(w.fr_analise)
    w.btn_dpv.place(relx=0.063, y=315, height=24, relwidth=0.88
            , bordermode='ignore')
    es.btnStyle(w.btn_dpv)
    w.btn_dpv.configure(text='''Iniciar''')
    w.btn_dpv.configure(width=167)
    w.btn_dpv.bind('<ButtonRelease-1>',lambda e:btn_iniciar(e))
    
    validation.updateInfo(float(w.et_PInicio.get()), float(w.et_PFim.get()), float(w.et_PPasso.get()), float(w.et_tPasso.get()))
    
#---- Operações de tratamento da curva ----#
    
def op_frame2param(frName, p1Name, p1Value, p2Name, p2Value, callback):
    destroyChildren(w.fr_analise)
    w.fr_analise.configure(text=frName)
    
    vcmd = w.fr_analise.register(validation.entryValidate)
    
    w.lb_Param1 = tk.Label(w.fr_analise, anchor="w")
    w.lb_Param1.place(relx=0.053, y=17, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_Param1)
    w.lb_Param1.configure(text=p1Name)

    w.et_Param1 = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_Param1.place(relx=0.59, y=18, height=20, width=74
            , bordermode='ignore')
    es.etStyle(w.et_Param1)
    w.et_Param1.configure(width=74)
    ctrl.validation.entryInsert(w.et_Param1, p1Value)

    
    w.lb_Param2 = tk.Label(w.fr_analise, anchor="w")
    w.lb_Param2.place(relx=0.053, y=43, height=21, width=91
            , bordermode='ignore')
    es.lbStyle(w.lb_Param2)
    w.lb_Param2.configure(text=p2Name)

    w.et_Param2 = tk.Entry(w.fr_analise, validate="key", validatecommand=(vcmd, '%d', '%i', '%P', '%S', '%W'))
    w.et_Param2.place(relx=0.59, y=44, height=20, width=74
            , bordermode='ignore')
    es.etStyle(w.et_Param2)
    ctrl.validation.entryInsert(w.et_Param2, p2Value)
    
    w.btn_Apply = tk.Button(w.fr_analise)
    w.btn_Apply.place(relx=0.063, y=315, height=24, relwidth=0.88
            , bordermode='ignore')
    es.btnStyle(w.btn_Apply)
    w.btn_Apply.configure(text='''Aplicar''')
    w.btn_Apply.configure(width=167)
    w.btn_Apply.bind('<ButtonRelease-1>',lambda x:aplicar(callback, (w.et_Param1.get(), w.et_Param2.get())))
    
def fd_PEAK():
    global curvePlot, spAt, cnvAt
    
    if curvePlot.size == 2:
        cv = np.take(curvePlot, 1)
        i = ctrl.operations.findPeak(cv.curveY)
        spAt.scatter(cv.curveX[i],cv.curveY[i])
        cnvAt.draw()
        w.lb_ConnInfo.configure(text="PICO\nPotencial = "+str(float("{0:.4f}".format(cv.curveX[i])))+"V\nCorrente = "+str(float("{0:.3f}".format(cv.curveY[i])))+"uA")
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nanalisar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Selecione uma curva")

def aplicar(callback, args):
    global curvePlot, curvesList
    
    if curvePlot.size == 2:
        c = np.take(curvePlot, 1)
        y = callback(c.curveY, *args)
        c2 = md.curve(c.curveName+"_"+callback.__name__, c.curveX, y)
        c2.curveX = c.curveX
        c2.curveY = y
        
        curvePlot = np.ndarray([])
        curvePlot = np.append(curvePlot, c2, axis=None)
        drawCurve()
        
        curvesList = np.append(curvesList, c2, axis=None)
        createMins()
        
    elif curvePlot.size > 2:
        w.lb_ConnInfo.configure(text="Ainda não é possível\nanalisar curvas unidas")
        
    elif curvePlot.size < 2:
        w.lb_ConnInfo.configure(text="Selecione uma curva")
    
""" apagar filhos de um frame

    for child in infoFrame.winfo_children():
    child.destroy()
    
"""
#! /usr/bin/env python #  -*- coding: utf-8 -*- # # Support module generated by PAGE version 4.20 #  in conjunction with Tcl version 8.6 #    Feb 18, 2019 11:55:48 AM -03  platform: Windows NT #    Feb 19, 2019 09:09:42 AM -03  platform: Windows NT Created on Mon Feb 18 10:08:04 2019  @author: <NAME> #from numpy import array, concatenate, ndarray, append, take, delete #font9 = "-family {Segoe UI} -size 9 -weight bold -slant roman "  \ #        "-underline 0 -overstrike 0" # Function which closes the window. ##########  Funções ########### Conectar Desconectar # Limpa o frame de miniaturas # Verifica se o potenciostato está conectado e inicia a análise x = np.arange(float(w.et_PInicio.get()), float(w.et_PFim.get()), float(w.et_PPasso.get()))         y = np.arange(0, x.size, 1)         c = md.curve("live Plot", x, y)         curvePlot = np.append(curvePlot, c) # Fundo de escala #, canvas) #curvePlot = np.append(curvePlot, np.take(curvesList, 1)) #if dpv: #dpv.curveName) #createCanvas() #spAt, cnvAt = drawCurve() #, title=cv.curveName) #canvas.draw() # Apaga miniaturas existentes # Cria miniaturas para cada curva na lista # Titulo superior das miniaturas # Canvas para desenhar a miniatura #toolbar = NavigationToolbar2Tk(canvas, w.fr_toolbar) #toolbar.update() #canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) #print("remover") #print("Igual") #print("c: "+ str(c.get())) #if t is p: #-----------------------------------------------------# #                      PAINEIS                        # #-----------------------------------------------------# #---- Painel DPV ----# DPV # Inicializa entradas que serão manipuladas Pot. Inicial (V) Pot. Final (V) Pot. Passo (V) Pot. Pulso (V) Tem. Pulso (s) Tem. Passo (s) Tem. equilíbrio (s) Int. Corrente SRate (V/s) Tem. Estimado (s) Nº Pontos Iniciar #---- Operações de tratamento da curva ----# Aplicar apagar filhos de um frame      for child in infoFrame.winfo_children():     child.destroy()