def search_by_categoria():
    def mostrar_lista(event):
        v = Toplevel()
        sc = Scrollbar(v)
        sc.pack(side=RIGHT, fill=Y)
        lb = Listbox(v, width=150, yscrollcommand=sc.set)

        ix = open_dir(DIR_INDEX)
        parameter = str(w.get())

        with ix.searcher() as searcher:
            query = QueryParser("categorias",
                                ix.schema).parse(f'"{parameter}"')
            results = searcher.search(query, limit=None)
            for r in results:
                lb.insert(END, f"Título: {r['titulo']}")
                lb.insert(
                    END,
                    f"Rango de fechas: {r['fecha_inicio']} - {r['fecha_fin']}")
                lb.insert(END, f"Cat: {r['categorias']}")
                lb.insert(END, '')
            lb.pack(side=LEFT, fill=BOTH)
            sc.config(command=lb.yview)

    categorias = listarCategorias()

    master = Tk()
    w = Spinbox(master, values=categorias)
    w.pack()

    w.bind("<Return>", mostrar_lista)
    w.pack(side=LEFT)
Esempio n. 2
0
    def makeFrameWidget(self):
        '''
        makes frame widget
        '''
        #make regular frame stuff -- label and tier
        self.frames_canvas = Canvas(self.canvas_frame,
                                    width=self.canvas_width,
                                    height=self.canvas_height,
                                    background='gray',
                                    highlightthickness=0)
        frames_label = Canvas(self.frame,
                              width=self.label_width,
                              height=self.canvas_height,
                              highlightthickness=0,
                              background='gray')
        frames_label.create_text(self.label_width,
                                 0,
                                 anchor='ne',
                                 justify='center',
                                 text='frames: ',
                                 width=self.label_width,
                                 activefill='blue')

        # make subframe to go on top of label canvas
        sbframe = Frame(frames_label)
        #put new widgets onto subframe
        offset = self.app.Data.getFileLevel('offset')
        if offset != None:
            self.frame_shift.set(offset)
        go_btn = Button(sbframe,
                        text='Offset',
                        command=self.shiftFrames,
                        takefocus=0)
        # minmax = len(self.app.Audio.sfile)*1000
        txtbox = Spinbox(sbframe,
                         textvariable=self.frame_shift,
                         width=7,
                         from_=-10000000,
                         to=10000000)
        txtbox.bind('<Escape>', lambda ev: sbframe.focus())
        txtbox.bind('<Return>', lambda ev: self.shiftFrames())
        go_btn.grid(row=0, column=0, sticky='e')
        txtbox.grid(row=0, column=1, sticky='e')
        # put subframe on canvas
        window = frames_label.create_window(self.label_width * .3,
                                            self.canvas_height / 3,
                                            anchor='nw',
                                            window=sbframe)

        self.TkWidgets.append({
            'name': self.frameTierName,
            'frames': self.frames_canvas,
            'frames-label': frames_label
        })

        self.frames_canvas.bind("<Button-1>", self.getClickedFrame)
Esempio n. 3
0
    def fillInfo(self, curRow: int, path: Path, name: str = None) -> None:
        rowLbl = zerofrmt(curRow)
        bg = self.litBg if (curRow % 2) else self.defBg
        # create container
        frm = Frame(master=self.scrFrm,
                    bg=bg,
                    relief='sunken',
                    bd=1)
        frm.columnconfigure(1, weight=1)
        frm.grid(column=0,
                 row=curRow,
                 sticky='ew')
        # create spinbox
        sbox = Spinbox(master=frm,
                       width=3,
                       bg=bg,
                       format=(f'%0{rndto}d' if rndto > 1 else ''),
                       takefocus=False,
                       from_=1,
                       to=self.lblRow,
                       increment=-1,
                       repeatdelay=(10**5),
                       validate='key',
                       validatecommand=self.checkValid)
        sbox.grid(column=0,
                  row=0)

        def btnpress(f=frm, s=sbox): self.updateList(f, s, True)
        def commit(_, f=frm, s=sbox): self.updateList(f, s)
        def cancel(_, f=frm, s=sbox): self.cancelChange(f, s)

        sbox.configure(command=btnpress)
        sbox.delete(0, 'end')
        if name:
            sbox.insert(0, rowLbl)
        else:
            name = path.name
        sbox.bind('<Return>', commit)
        sbox.bind('<Escape>', cancel)
        # create name label
        lbl = Label(master=frm,
                    text=name,
                    bg=bg)
        lbl.grid(column=1,
                 row=0,
                 sticky='w')
        # save to data dict
        self.data[rowLbl] = dict(frm=frm,
                                 sbox=sbox,
                                 lbl=lbl,
                                 path=path,
                                 name=name)
Esempio n. 4
0
 def pack(self):
     key = self.parent.app.environment.get_var_key(self.variable)
     if (self.parent.app.environment.is_visible(key)):
         label = Label(master=self.parent, cnf={
             'text': self.label,
         })
         label.pack()
         w = Spinbox(self.parent,
                     from_=0,
                     to=1000000,
                     textvariable=self.variable,
                     command=self.parent.app.reload)
         w.bind('<FocusOut>', self.parent.app.reload)
         w.pack()
Esempio n. 5
0
class View(Frame):
    def __init__(self, master, controller, label, width, minimum, maximum,
                 current, *args, **kwargs):
        super(View, self).__init__(master, *args, **kwargs)
        self._controller = controller
        self._create_label(label, width)
        self._create_spinbox(minimum, maximum)
        self._create_scale(minimum, maximum)

    def w_label(self):
        return self._label

    def w_spinbox(self):
        return self._spinbox

    def w_scale(self):
        return self._scale

    def _create_label(self, label, width):
        self._label = LabelTtk(self, text=label)

        if width:
            self._label.config(width=width)

        self._label.pack(side='left', anchor='s')

    def _create_spinbox(self, minimum, maximum):
        self._spinbox = Spinbox(self, from_=minimum, to=maximum)

        self._spinbox['command'] = lambda: \
            self._controller.set_current(int(self._spinbox.get()))

        self._spinbox.bind('<Return>', lambda e: \
            self._controller.set_current(self._spinbox.get()))

        self._spinbox.pack(side="left", anchor="s")

    def _create_scale(self, minimum, maximum):
        self._scale = Scale(self,
                            orient="horizontal",
                            from_=minimum,
                            to=maximum)

        self._scale['command'] = lambda e: \
            self._controller.set_current(self._scale.get())

        self._scale.pack(side="left", fill="x", expand=True, anchor="s")
Esempio n. 6
0
 def new_map(event):
     dialog = Toplevel(widget)
     form = Frame(dialog)
     Label(form, text='Width:').grid(row=0, column=0)
     Label(form, text='Height:').grid(row=1, column=0)
     size = [1, 1]
     comm = (lambda ix: (lambda event=None: size.__setitem__(ix, wb.get() + (event.char if event else ''))))
     wv = IntVar(value=10)
     wb = Spinbox(form, from_=1, to=65535, command=comm(0), textvariable=wv)
     wb.bind('<Key>', comm(0))
     wb.grid(row=0, column=1)
     hv = IntVar(value=10)
     hb = Spinbox(form, from_=1, to=65535, command=comm(1), textvariable=hv)
     hb.bind('<Key>', comm(1))
     hb.grid(row=1, column=1)
     form.pack()
     dialog.transient(widget)
     dialog.grab_set()
     wb.focus_set()
     widget.wait_window(dialog)
     create_new_map(wv.get(), hv.get())
Esempio n. 7
0
    def __init__(self, master, app, *args, **kwargs):
        super().__init__(master, *args, **kwargs)

        delayvarlabframe = Frame(self)
        delayvarlabframe.pack(side='top', fill='x')
        l = Label(delayvarlabframe, text="Delay Variables", width=20, font='Verdana 8')
        l.pack(side='left', padx=(30 * len(app.delay_tuners))/2, anchor='n', pady=5)


        delaytunerframe = Frame(self)
        delaytunerframe.pack(side='top', fill='x')
        app.binds = []

        for iter, (notation, var) in enumerate(app.delay_tuners.items()):
            sb = Spinbox(delaytunerframe, to=100.00, from_=0.00, textvariable=var, increment=.001, width=6, command=lambda: app.tune_var())
            bind = sb.bind('<Key>', app.tune_delay_variable)
            app.binds.append((sb, bind))
            l = Label(delaytunerframe, text=notation, width=2, font='Verdana 8')
            l.pack(side='left', padx=5, anchor='n')
            sb.pack(side='left', padx=5, anchor='n')
            if iter == 0:
                default_aavarname = notation

        Label(delayvarlabframe, text="Freq.", font="Verdana 8").pack(side='right', padx=15)
        Label(delayvarlabframe, text="Val.", font="Verdana 8").pack(side='right', padx=25)
        Label(delayvarlabframe, text="Var.", font="Verdana 8").pack(side='right', padx=35)
        Label(delayvarlabframe, text="Auto Adjustment", font="Verdana 8").pack(side='right', padx=0)




        app.aafreqsb = Spinbox(delaytunerframe, to=1000, from_=0, textvariable=app.aafreq, increment=1, width=6)
        app.aafreqsb.pack(side='right', padx=5)

        app.aavalsb = Spinbox(delaytunerframe, to=0.1, from_=-0.1, textvariable=app.aaval, increment=0.001, width=6)
        app.aavalsb.pack(side='right', padx=5)

        app.auto_adjbox = Combobox(delaytunerframe, width=8, values=[var for var in list(app.delay_tuners)], textvariable=app.aavar)
        app.auto_adjbox.pack(side='right', padx=5)
        app.auto_adjbox.set(default_aavarname)

        app.aa_enabled_var = StringVar(value='0')
        app.enable_aa_btn = Checkbutton(delaytunerframe)
        app.enable_aa_btn.pack(side='right', padx=55)
        app.enable_aa_btn.bind("<Button 1>", lambda e: app.toggle_auto_adjustment(event=e))
        app.enable_aa_btn.invoke()
        app.enable_aa_btn.invoke()
Esempio n. 8
0
    def create_spinbox(self):
        P0, widget_dims, board_dims = self.board.get_geometry()
        x, y = P0
        width, height = widget_dims
        board_width, board_height = board_dims

        x, y = x / board_width, y / board_height
        width, height = width / board_width, height / board_height

        box = Spinbox(self.board)
        box.place(relx=x, rely=y, relheight=height, relwidth=width, anchor="nw")
        self.board.delete("line")

        items = [item for item in box.keys() if len(item) > 2]

        box.bind("<Enter>", lambda event: self.get_widget_info(box))
        box.bind("<Leave>", lambda event: self.focus_out())
        box.bind("<Button-3>", lambda event: self.modify(box, items))

        self.manager.switch(box, items)
Esempio n. 9
0
File: gui.py Progetto: babab/DisPass
    def createWidgets(self):
        '''Create and align widgets'''

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.passwordout = StringVar()
        self.passwordout.set('- No password generated -')
        self.isnew = IntVar()

        ttitle = Label(self, text=versionStr, font=self.getFont(4))
        wisnew = Checkbutton(self, height=2, font=self.getFont(),
                             text=('This is a new password, that I have not '
                                   'used before'),
                             variable=self.isnew, command=self.toggleCheck)
        tlabel = Label(self, text='Label', font=self.getFont(2))
        tpasswordin1 = Label(self, text='Password', font=self.getFont(2))
        tpasswordin2 = Label(self, text='Password (again)',
                             font=self.getFont(2))
        tlength = Label(self, text='Length', font=self.getFont(2))
        talgorithm = Label(self, text='Algorithm', font=self.getFont(2))
        tsequence = Label(self, text='Sequence #', font=self.getFont(2))
        self.label = ttk.Combobox(self, width=27, font=self.getFont(),
                                  postcommand=self.filterLabels)
        self.passwordin1 = Entry(self, width=27, font=self.getFont(), show="*")
        self.passwordin2 = Entry(self, width=27, font=self.getFont(), show="*",
                                 state=DISABLED)
        length = Spinbox(self, width=3, font=self.getFont, from_=9,
                         to=171, textvariable=self.lengthVar)
        self.algorithm = ttk.Combobox(self, width=27, font=self.getFont(),
                                      values=algos.algorithms)
        sequence = Spinbox(self, width=3, font=self.getFont, from_=1,
                           to=sys.maxsize, textvariable=self.sequenceVar)
        genbutton = Button(self, text="Generate password",
                           font=self.getFont(), command=self.validateAndShow,
                           default="active")
        clrbutton = Button(self, text="Clear fields", font=self.getFont(),
                           command=self.clearIO)
        self.result = Entry(self, font=self.getFont(4),
                            textvariable=self.passwordout, state="readonly",
                            fg="black", readonlybackground="gray")

        # Keybindings
        self.passwordin1.bind('<Return>', lambda e: genbutton.invoke())
        self.passwordin2.bind('<Return>', lambda e: genbutton.invoke())
        length.bind('<Return>', lambda e: genbutton.invoke())
        self.algorithm.bind('<Return>', lambda e: genbutton.invoke())
        sequence.bind('<Return>', lambda e: genbutton.invoke())
        self.master.bind('<Control-q>', lambda e: self.quit())
        self.master.bind('<Escape>', lambda e: self.reset())
        self.label.bind('<<ComboboxSelected>>', self.labelSelected)
        self.label.bind('<FocusOut>', self.labelFocusOut)

        # Layout widgets in a grid
        ttitle.grid(row=0, column=0, sticky=N + S + E + W, columnspan=2)
        wisnew.grid(row=1, column=0, sticky=N + S + E + W, columnspan=2)

        tlabel.grid(row=2, column=0, sticky=N + S + W)
        self.label.grid(row=2, column=1, sticky=N + S + E + W)

        tpasswordin1.grid(row=3, column=0, sticky=N + S + W)
        self.passwordin1.grid(row=3, column=1, sticky=N + S + E + W)

        tpasswordin2.grid(row=4, column=0, sticky=N + S + W)
        self.passwordin2.grid(row=4, column=1, sticky=N + S + E + W)

        tlength.grid(row=5, column=0, sticky=N + S + W)
        length.grid(row=5, column=1, sticky=N + S + E + W)

        talgorithm.grid(row=6, column=0, sticky=N + S + W)
        self.algorithm.grid(row=6, column=1, sticky=N + S + E + W)

        tsequence.grid(row=7, column=0, sticky=N + S + W)
        sequence.grid(row=7, column=1, sticky=N + S + E + W)

        clrbutton.grid(row=8, column=0, sticky=N + S + E + W, columnspan=2)
        genbutton.grid(row=9, column=0, sticky=N + S + E + W, columnspan=2)
        self.result.grid(row=10, column=0, sticky=N + S + E + W, columnspan=2)

        # Initial values
        self.algorithm.set(self.settings.algorithm)

        # Initially, set focus on self.label
        self.label.focus_set()
Esempio n. 10
0
class CompetitorRegistrationWindow(Toplevel):
    def __init__(self, parent, db, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)
        self.parent = parent
        self.db = db
        self.title('Register new competitor...')
        self.hr1 = Frame(self, height=1, width=500, bg="gray")  # creates a gray line under the registration

        self.fnameLabel = Label(self, text='First:')
        self.lnameLabel = Label(self, text='Last:')
        self.levelLabel = Label(self, text='Level:')
        self.sexLabel = Label(self, text='Sex:')
        self.ageLabel = Label(self, text='Age:')

        self.sexValue = StringVar()
        self.sexValue.set('M')

        self.levelValues = ('Beginner', 'Intermediate', 'Advanced', 'Open')

        self.fnameEntry = EntryWithPlaceholder(self, placeholder='John', width=30)
        self.lnameEntry = EntryWithPlaceholder(self, placeholder='Doe', width=30)
        self.levelEntry = Spinbox(self, values=self.levelValues)
        self.sexEntryM = Radiobutton(self, text='M', variable=self.sexValue, value='M')
        self.sexEntryF = Radiobutton(self, text='F', variable=self.sexValue, value='F')
        self.ageEntry = Spinbox(self, from_=1, to=100, width=6)
        self.registerButton = Button(self, text='Register', command=self.register_competitor)

        self.ageEntry.delete('0', 'end')
        self.ageEntry.insert(0, 20)

        self.fnameEntry.bind('<Return>', self.register_competitor)  # these bind all the entries to <return>
        self.lnameEntry.bind('<Return>', self.register_competitor)  # meaning that hitting enter while within any of
        self.levelEntry.bind('<Return>', self.register_competitor)  # of them will submit the form to the
        self.sexEntryF.bind('<Return>', self.register_competitor)  # register_competitor function
        self.sexEntryM.bind('<Return>', self.register_competitor)
        self.ageEntry.bind('<Return>', self.register_competitor)
        self.registerButton.bind('<Return>', self.register_competitor)

        self.fnameLabel.grid(row=1, column=0)
        self.fnameEntry.grid(row=1, column=1, columnspan=4)
        self.lnameLabel.grid(row=1, column=5)
        self.lnameEntry.grid(row=1, column=6, columnspan=4)
        self.levelLabel.grid(row=2, column=0)
        self.levelEntry.grid(row=2, column=1, columnspan=2)
        self.sexLabel.grid(row=2, column=3)
        self.sexEntryM.grid(row=2, column=4)
        self.sexEntryF.grid(row=2, column=5)
        self.ageLabel.grid(row=2, column=6)
        self.ageEntry.grid(row=2, column=7)
        self.registerButton.grid(row=2, column=8)

    def register_competitor(self, *args):
        self.db.insert_row((self.fnameEntry.get(),
                            self.lnameEntry.get(),
                            self.levelEntry.get(),
                            self.sexValue.get(),
                            self.ageEntry.get(),
                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
        self.clear_registration()
        self.fnameEntry.focus_set()

    def clear_registration(self):
        self.fnameEntry.replace_placeholder()
        self.lnameEntry.replace_placeholder()
        self.levelEntry.setvar(self.levelValues[0], value='1')
        self.sexValue.set('M')
        self.ageEntry.delete(0, 'end')
        self.ageEntry.insert(0, 20)
Esempio n. 11
0
class pedidos(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.func = functions(self)
        self.pathLocation = get_secret("MAIN_PATH")
        self.matriz = StringVar()
        self.solicitante = StringVar()
        self.produto = StringVar()
        self.pedido = []
        self.index = IntVar()

    def addPedido(self, logoObject):

        # Frame de adicionar pedidos.
        self.frameAdd = Toplevel(self)
        for col in range(8):
            Grid.columnconfigure(self.frameAdd, col, weight=1)

        self.frameAdd.wm_title("Adicionar Novo Pedido")
        self.frameAdd.bind("<Escape>", lambda _: self.frameAdd.destroy())
        logoFrame = Frame(self.frameAdd)

        logoFrame.grid(row=0, column=0, columnspan=7, pady=(20, 0), sticky='N')
        labelImagem = Label(logoFrame)
        labelImagem['image'] = logoObject
        labelImagem.image = logoObject
        labelImagem.pack()

        # Algumas declarações.

        listLabel = []
        listaProdutos = self.func.lerProdutos()
        data = StringVar()
        data.set(strftime("%d/%m/%y"))
        check = IntVar()
        check.set(1)
        spinBox = [
            "001", "002", "003", "004", "005", "006", "007", "008", "009",
            "010"
        ]

        self.pedido.clear()

        self.produto.set(listaProdutos[0])

        self.matriz.set(int(self.func.getCI_Atual()) + 1)

        self.index.set(0)

        # Tratamento de erros na leitura de arquivos.
        if listaProdutos == "Error" or self.matriz.get() == "-666":
            self.frameAdd.destroy()
        else:

            # Labels para Entrada de dados.

            del listLabel[:]

            for _ in range(7):
                listLabel.append(Label(self.frameAdd))

            listLabel[0]['text'] = "C.I Matriz"
            listLabel[0].grid(row=1,
                              column=0,
                              pady=(10, 0),
                              padx=(10, 0),
                              sticky='N')

            listLabel[1]['text'] = "C.I Filial"
            listLabel[1]['fg'] = 'red'
            listLabel[1].grid(row=1, column=1, pady=(10, 0), sticky='N')

            listLabel[2]['text'] = "Loja"
            listLabel[2]['fg'] = 'red'
            listLabel[2].grid(row=1, column=2, pady=(10, 0), sticky='N')

            listLabel[3]['text'] = "Solicitante"
            listLabel[3]['fg'] = 'red'
            listLabel[3].grid(row=1, column=3, pady=(10, 0), sticky='N')

            listLabel[4]['text'] = "Data de Envio"
            listLabel[4]['fg'] = 'red'
            listLabel[4].grid(row=1, column=4, pady=(10, 0), sticky='N')

            listLabel[5]['text'] = "Quantidade"
            listLabel[5]['fg'] = 'red'
            listLabel[5].grid(row=1, column=5, pady=(10, 0), sticky='N')

            listLabel[6]['text'] = "Produto"
            listLabel[6]['fg'] = 'red'
            listLabel[6].grid(row=1,
                              column=6,
                              pady=(10, 0),
                              padx=(0, 10),
                              sticky='N')

            # O proprio sistema quem identifica e
            # coloca o valor do C.I da matriz!
            self.entryMatriz = Entry(self.frameAdd)
            self.entryMatriz['textvariable'] = self.matriz
            self.entryMatriz['width'] = 4
            self.entryMatriz['state'] = DISABLED
            self.entryMatriz['takefocus'] = False
            self.entryMatriz.grid(row=2, column=0, padx=(40, 0), sticky='N')

            def verfNumero(flag):
                if flag == 1:
                    self.entryFilial.insert(0, "S/Nº")
                    self.entryFilial.config(state=DISABLED)
                    self.entryLoja.focus()
                elif flag == 0:
                    self.entryFilial.config(state=NORMAL)
                    self.entryFilial.delete(0, END)
                    self.entryFilial.focus()

            self.entryFilial = Entry(self.frameAdd)
            self.entryFilial['width'] = 5
            self.entryFilial.insert(0, "S/Nº")
            self.entryFilial.config(state=DISABLED)
            self.entryFilial.bind("<Tab>", self.setNext)
            self.entryFilial.grid(row=2, column=1, sticky='N')

            self.checkBox = Checkbutton(self.frameAdd)
            self.checkBox['text'] = "Sem Número"
            self.checkBox['variable'] = check
            self.checkBox['command'] = lambda: verfNumero(check.get())
            self.checkBox['onvalue'] = 1
            self.checkBox['offvalue'] = 0
            self.checkBox.grid(row=3, column=1, sticky='N')

            self.entryLoja = Entry(self.frameAdd)
            self.entryLoja['width'] = 4
            self.entryLoja.focus()
            self.entryLoja.grid(row=2, column=2, sticky='N')

            self.listaSolicitantes = Combobox(self.frameAdd)
            self.listaSolicitantes['postcommand'] = self.localizaLoja
            self.listaSolicitantes['state'] = 'readonly'
            self.listaSolicitantes.grid(row=2,
                                        column=3,
                                        rowspan=3,
                                        padx=(20, 10),
                                        pady=(7, 0),
                                        sticky='N')

            # A data de envio é obtida automaticamente.

            self.entryDataEnvio = Entry(self.frameAdd)
            self.entryDataEnvio['textvariable'] = data
            self.entryDataEnvio['width'] = 8
            self.entryDataEnvio['state'] = DISABLED
            self.entryDataEnvio['takefocus'] = False
            self.entryDataEnvio.grid(row=2, column=4, sticky='N')

            self.spinQuantidade = Spinbox(self.frameAdd)
            self.spinQuantidade['width'] = 3
            self.spinQuantidade['values'] = spinBox
            self.spinQuantidade.bind("<Return>", self.setNext)
            self.spinQuantidade.grid(row=2, column=5, sticky='N')

            self.selecionarProdutos = Combobox(self.frameAdd)
            self.selecionarProdutos['values'] = listaProdutos
            self.selecionarProdutos.grid(row=2,
                                         column=6,
                                         padx=(0, 20),
                                         sticky='N')
            self.selecionarProdutos.current(0)

            # Botões

            button_avancar = Button(self.frameAdd)
            button_avancar['width'] = 15
            button_avancar['text'] = "Avançar"
            button_avancar['command'] = self.func.salvarPedido
            button_avancar.bind("<Return>", lambda _: self.func.salvarPedido())
            button_avancar.grid(row=6,
                                column=1,
                                columnspan=3,
                                pady=(0, 20),
                                sticky='N')

            cancelButton = Button(self.frameAdd)
            cancelButton['width'] = 15
            cancelButton['text'] = "Cancelar"
            cancelButton['command'] = self.frameAdd.destroy
            cancelButton.bind("<Return>", lambda _: self.frameAdd.destroy())
            cancelButton.grid(row=6,
                              column=5,
                              columnspan=3,
                              pady=(0, 20),
                              sticky='N')

    def localizaLoja(self):
        loja = self.entryLoja.get().upper()
        _path = os.path.abspath(os.path.join(self.pathLocation,
                                             "Filiais.json"))
        with open(_path, 'r', encoding=ENCODING) as fp:
            filiais = json.load(fp)

        if loja in filiais:
            self.listaSolicitantes['state'] = NORMAL
            self.listaSolicitantes['values'] = []

            _path = os.path.abspath(
                os.path.join(self.pathLocation, "Lojas", f"{loja}.json"))
            with open(_path, 'r+', encoding=ENCODING) as file:

                self.listaSolicitantes['values'] = json.load(file)
                self.listaSolicitantes.current(0)

            self.listaSolicitantes.grid(row=2,
                                        column=3,
                                        rowspan=3,
                                        padx=(20, 10),
                                        pady=(7, 0),
                                        sticky='N')

        else:
            self.listaSolicitantes.set('')
            self.listaSolicitantes['values'] = []
            self.listaSolicitantes['state'] = 'readonly'
            message = """Filial "%s" nao econtrada no sistema!
                    \nVerifique o nome da filial e tente novamente.""" % loja

            messagebox.showwarning("ERRO", message, parent=self.frameAdd)
            self.entryLoja.focus()

    def getPedido(self):
        flag = True
        # Obetem as entradas e as coloca em ordem em uma lista.

        self.pedido.append(self.entryMatriz.get().rstrip())
        self.pedido.append(self.entryFilial.get().rstrip())
        self.pedido.append(self.listaSolicitantes.get().rstrip())
        self.pedido.append(self.entryLoja.get().upper().rstrip())
        self.pedido.append(self.entryDataEnvio.get().rstrip())
        self.pedido.append(self.spinQuantidade.get().rstrip())
        self.pedido.append(self.selecionarProdutos.get().rstrip())

        for verify in self.pedido:
            if verify == '' or verify == ():
                flag = False
                break

        if flag is True:

            # Limpa os campos de entrada.
            self.entryMatriz.delete(0, END)
            self.entryFilial.delete(0, END)
            self.solicitante.set('')
            self.entryLoja.delete(0, END)
            self.entryDataEnvio.delete(0, END)
            self.spinQuantidade.delete(0, END)
            self.produto.set("Cilindro DR-3302")
            self.frameAdd.destroy()
            return self.pedido
        else:
            self.pedido.clear()
            return "ERROR"

    def getFrame(self):
        return self.frameAdd

    def getMatriz(self):
        return self.matriz.get()

    @staticmethod
    def setNext(event):
        print(event.widget.tk_focusNext())
        event.widget.tk_focusNext().focus()
        return "break"
Esempio n. 12
0
class ReviewFitPage(Frame): 
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.controller = parent
        title = Label(self,text="Fit Review",font=("Arial",14,"bold"))
        title.grid(row=0,column=0,columnspan=6)
        self.f = Figure(figsize=(5,5), dpi=100)
        self.a = self.f.add_subplot(111)             
        Label(self, text="Left Bound:").grid(row=1,column=6)
        Label(self, text="Right Bound:").grid(row=1,column=7)
        peakSelectorButton =  Button(self, text="Manually Choose Element", command=self.send_to_mes)
        peakSelectorButton.grid(row=5,column=6)
        integrateButton = Button(self, text="Manually Integrate and Choose Element", command = self.send_to_mi)
        integrateButton.grid(row=5,column=7)
        acceptButton = Button(self, text="Fit looks good, let the program continue", command=self.submit)
        acceptButton.grid(row=6,column=6)
        ignoreButton = Button(self, text="Ignore this data", command = lambda:self.controller.peakCounter.set(self.controller.peakCounter.get()+1))
        ignoreButton.grid(row=6,column=7)
        self.KnownPeaksFrame = Frame(self)
        Label(self.KnownPeaksFrame, text="Peak Information (Center, Amplitude, Width)").grid(row=0, column=0, columnspan=2)
        
        self.newPeakEntry = Entry(self.KnownPeaksFrame)
        self.newPeakEntry.grid(row=1,column=0)
        self.newPeakEntry.insert(0,"Enter Peak Energy")
        self.newPeakEntry.bind("<FocusIn>",self.clear_new_entry)
        
        Button(self.KnownPeaksFrame, text="Add", command=lambda:self.add_peak(self.newPeakEntry.get())).grid(row=1,column=1)
        
        self.KnownPeaksFrame.grid(row=3,column=6, columnspan=2)
        Button(self, text="Reanalyze", command=self.reanalyze).grid(row=4,column=6,columnspan=2)
        self.energies = []
        self.cps = []
        self.slope = 0
        self.intercept = 0
        self.ctrs = []
        self.annots = []
        self.fill = None
        self.peakGUIList = []
        self.removeBtns = []
    def populate_values(self, startInd, endInd, peaks, variances):
        self.a.cla()
        self.startInd = startInd
        self.energies = self.controller.file1Energies[startInd-20:endInd+21]
        self.cps = self.controller.file1CPS[startInd-20:endInd+21]
        self.variances = list(variances)
        if len(peaks) > 0:
            self.ctrs = np.array(peaks[2::3])
            self.amps = np.array(peaks[3::3])
            self.wids = np.array(peaks[4::3])
            self.slope = peaks[0]
            self.intercept = peaks[1]
            poss = chain.from_iterable(self.get_possibilites(True))
            poss = list(k for k,_ in groupby(poss))
            self.peaks = list(peaks[2:])
            fitX = np.arange(self.energies[20],self.energies[-20],.01)
            self.fitX = fitX
            backgroundY = fitX * peaks[0] + np.array([peaks[1]]*len(fitX))
            self.backgroundY = backgroundY
            fitY = self.controller.multiple_gaussian_and_secant(fitX,*peaks)
            self.a.plot(fitX, fitY, "r-", label = "Fit")
            fullAmps = self.amps + (peaks[0] * self.ctrs + peaks[1]) 
            self.peakPoints = self.a.plot(self.ctrs, fullAmps,"go",label="Found Peaks",picker=6)[0]
            self.peakPoints.set_pickradius(10)
            self.backgroundLine = self.a.plot(fitX,backgroundY,"k-", label = "Background")
            self.f.canvas.mpl_connect('motion_notify_event', self.on_plot_hover)
        self.a.plot(self.energies, self.cps,"bo", label="Observed Data")
        self.a.set_xlim(self.energies[20],self.energies[-20])
        self.canvas = FigureCanvasTkAgg(self.f, self)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=1,column=0,columnspan=6, rowspan=6)
        self.a.legend(loc='upper right', prop={'size': 8})
        toolbarFrame = Frame(self)
        toolbarFrame.grid(row=7,column=0,columnspan=6, sticky="w")
        toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame)
        self.spinboxLeftVal = DoubleVar()
        self.spinboxLeft = Spinbox(self, values=self.energies[:-20], command = self.update_right, textvariable = self.spinboxLeftVal)
        self.spinboxLeft.bind("<Return>",lambda x:self.update_right())
        self.spinboxLeft.bind("<FocusOut>",lambda x:self.update_right())
        self.spinboxLeftVal.set(self.energies[20])
        self.spinboxLeft.grid(row=2,column=6)
        self.spinboxRightVal = DoubleVar()
        self.spinboxRight = Spinbox(self, values = self.energies[21:], command = self.update_left, textvariable = self.spinboxRightVal)
        self.spinboxRight.bind("<Return>",lambda x:self.update_left())
        self.spinboxRight.bind("<FocusOut>",lambda x:self.update_left())
        self.spinboxRightVal.set(self.energies[-20])
        self.spinboxRight.grid(row=2,column=7)
        for i in self.peakGUIList:
            i.destroy()
        for i in self.removeBtns:
            i.destroy()
        self.peakGUIList = []
        self.removeBtns = []
        for i in range(len(self.ctrs)):
            self.peakGUIList.append(Label(self.KnownPeaksFrame, text="{:5f}, {:5f}, {:5f}".format(self.ctrs[i],self.amps[i],self.wids[i])))
            self.removeBtns.append(Button(self.KnownPeaksFrame, text="Remove", command=lambda temp=i:self.remove_peak(temp)))
            self.peakGUIList[i].grid(row=i+2,column=0)
            self.removeBtns[i].grid(row=i+2,column=1)
    def remove_peak(self, ind):
        self.peakGUIList[ind].destroy()
        del self.peakGUIList[ind]
        self.removeBtns[-1].destroy()
        del self.removeBtns[-1]
    def add_peak(self, loc):
        try:
            loc = float(loc)
        except ValueError:
            return None
        self.reset_new_entry()
        i=0
        while self.energies[i] < loc:
            i += 1
        self.peakGUIList.append(Label(self.KnownPeaksFrame, text="{:5f}, {:5f}, 1.00".format(self.energies[i], self.cps[i])))
        self.removeBtns.append(Button(self.KnownPeaksFrame, text="Remove", command=lambda temp=len(self.peakGUIList)-1:self.remove_peak(temp)))
        self.peakGUIList[-1].grid(row=len(self.peakGUIList)+1, column=0)
        self.removeBtns[-1].grid(row=len(self.peakGUIList)+1, column=1)
    def on_plot_hover(self, e):
        cont, ind = self.peakPoints.contains(e)
        if cont and self.fill == None:
            x = self.peakPoints.get_xdata()[ind["ind"][0]]
            y = self.peakPoints.get_ydata()[ind["ind"][0]] - (self.slope * x + self.intercept)
            self.fill = self.a.fill_between(self.fitX, self.backgroundY, self.backgroundY + self.controller.multiple_gaussian(self.fitX, x, y, self.wids[np.where(self.ctrs == x)[0][0]]), facecolor='red', alpha=0.5)
            self.canvas.draw()
        else:
            if self.fill != None:
                self.fill.remove()
                self.fill = None
                self.canvas.draw()
    #TODO: add manual entry flag, and call it with a keybind from the spinboxes
    def update_left(self):
        temp = self.spinboxLeftVal.get()
        if self.spinboxRightVal.get() > self.energies[-1]:
            messagebox.showinfo("Out of Bounds","Please enter an X value within the currently plotted points")
            self.spinboxRightVal.set(self.energies[-20])
            return None
        try:
            newRange = self.energies[:np.where(self.energies==self.spinboxRightVal.get())[0][0]]
        except IndexError:
            newRange = self.energies[:binary_search_find_nearest(self.energies, self.spinboxRightVal.get())]
        self.spinboxLeft.configure(values=newRange)
        self.spinboxLeftVal.set(temp)
    def update_right(self):
        temp = self.spinboxRightVal.get()
        if self.spinboxLeftVal.get() < self.energies[0]:
            messagebox.showinfo("Out of Bounds","Please enter an X value within the currently plotted points")
            self.spinboxLeftVal.set(self.energies[20])
            return None
        try:
            newRange = self.energies[np.where(self.energies==self.spinboxLeftVal.get())[0][0]+1:]
        except IndexError:
            newRange = self.energies[binary_search_find_nearest(self.energies, self.spinboxLeftVal.get()):]
        self.spinboxRight.configure(values=newRange)
        self.spinboxRightVal.set(temp)
    def reanalyze(self):
        try:
            lowIndex = np.where(self.energies==self.spinboxLeftVal.get())[0][0]
            highIndex = np.where(self.energies==self.spinboxRightVal.get())[0][0] + 1
        except IndexError:
            lowIndex = binary_search_find_nearest(self.energies, self.spinboxLeftVal.get())
            highIndex = binary_search_find_nearest(self.energies, self.spinboxRightVal.get())
        guesses = [[float(j) for j in i.cget("text").split(", ")] for i in self.peakGUIList]
        guesses = list(chain.from_iterable(guesses))
        guesses = [self.slope, self.intercept] + guesses
        try:
            popt, pcov = curve_fit(self.controller.multiple_gaussian_and_secant, xdata = self.energies[lowIndex:highIndex], ydata = self.cps[lowIndex:highIndex], p0 = np.array(guesses))
            self.populate_values(self.startInd - 20 + lowIndex, self.startInd - 20 + highIndex, popt, np.diag(pcov)[2:])
        except RuntimeError:
            messagebox.showwarning("No fit found", "No good peak fit could be determined. Try entering fewer centroids.")
        
    def clear_new_entry(self, _):
        self.newPeakEntry.delete(0,"end")
    def reset_new_entry(self):
        self.newPeakEntry.delete(0,"end")
        self.newPeakEntry.insert(0,"Enter Peak Energy")
    def get_possibilites(self, MP):
        if MP:#Multiple peaks
            return [self.controller.get_possibilites_list(c) for c in self.ctrs]
        else:
            return self.controller.get_possibilites_list((self.energies[20]+self.energies[-20])/2)
    def send_to_mi(self):
        #TODO: get left and right selectors
        try:
            left = float(self.spinboxLeftVal.get())
            right = float(self.spinboxRightVal.get())
        except ValueError:
            messagebox.showinfo("Bad Input","Please enter in-range floating point numbers for the bounds.")
        if left < self.energies[0] or right > self.energies[-1]:
            messagebox.showinfo("Bad Input","Please enter in-range floating point numbers for the bounds.")
            return None
        r = binary_search_find_nearest(self.energies, right)
        l = binary_search_find_nearest(self.energies, left)
        self.controller.show_frame(ManualIntegrationPage)
        self.controller.frames[ManualIntegrationPage].populate_values(self.energies[l:r], self.cps[l:r])
        self.controller.frames[ManualIntegrationPage].add_peak_selector(self.get_possibilites(False))
        
    def send_to_mes(self):
        cpsNoBgd = [j - (self.energies[i] * self.slope + self.intercept) for i,j in enumerate(self.cps)]
        self.controller.show_frame(ManualElementSelect)
        self.controller.frames[ManualElementSelect].populate_values(self.energies[20:-20], cpsNoBgd[20:-20])
        self.controller.frames[ManualElementSelect].add_peak_selectors(self.peaks,self.get_possibilites(True),self.variances)
    def submit(self):
        self.controller.add_auto_peaks(self.peaks, list(self.variances))
        self.controller.increment_peak_counter()
Esempio n. 13
0
                          command=changeDim)

# INITIAL VALUES
spinboxDegree.delete(0, END)
spinboxDegree.insert(0, ui.ndeg)
# spinboxDegree.bind("<Increment>", updateAll)

labelSeg = ttk.Label(master=sideFrame, text="Segmentos:")
spinboxSeg = Spinbox(master=sideFrame,
                     from_=1,
                     to=5000,
                     textvariable=ui.nseg,
                     width=7,
                     command=updateAll)

spinboxDegree.bind('<Return>', updateAll)
spinboxSeg.bind('<Return>', updateAll)
# INITIAL VALUES
spinboxSeg.delete(0, END)
spinboxSeg.insert(0, ui.nseg)
# spinboxSeg.bind("<Increment>", updateAll)

label3D2D = ttk.Label(master=sideFrame, text="Dimensão dos pontos:")

# THIRD COLUMN
labelExamples = ttk.Label(master=sideFrame, text=">>>Exemplos<<<")
labelExamples2D = ttk.Label(master=sideFrame, text="Exemplos 2D:")
buttonEx1 = ttk.Button(master=sideFrame,
                       text="Exemplo 1",
                       command=lambda: callExButton(1))
buttonEx2 = ttk.Button(master=sideFrame,
Esempio n. 14
0
class PVapplicaton(Frame):
    """
    classdocs
    """

    def __init__(self, master=None):
        """
        Constructor
        """
        Frame.__init__(self, master, name='pvApplication',
                       bg='black', padx=5, pady=5)
        # set black background, pad sides with 15 points, top/bottom 5 points
        # fill=BOTH fills in padding with background color
        # w/o fill=BOTH padding is default color
        # side=TOP is the default
        self.pack(fill=BOTH)
        master.resizable(False, False)  # not resizable in x or y
        master.title(PVAPP_TXT)  # set title bar of master (a.k.a. root)
        master.protocol("WM_DELETE_WINDOW", self._quit)  # close window to quit

        self.validationConstants = self.readJSON('validationConstants')
        self.messagetext = self.readJSON('messagetext' + '.' + LANGUAGE)
        MAX_STRINGS = self.validationConstants["pvapplication"]["numStrs"]
        MAX_MODULES = self.validationConstants["pvapplication"]["numMods"]
        MAX_SUNS = self.validationConstants["pvapplication"]["sysEe"]
        CAPTION_FONT = nametofont('TkCaptionFont')  # font for titles

        # PVsystem
        pvSys = self.pvSys = PVsystem()

        # variables
        numStrs = self.numStrs = IntVar(self, NUMBERSTRS, 'numStrs')
        numMods = self.numMods = IntVar(self, NUMBERMODS, 'numMods')
        numCells = self.numCells = IntVar(self, NUMBERCELLS, 'numCells')
        txtIsys = self.txtIsys = DoubleVar(self, name='txtIsys')
        txtVsys = self.txtVsys = DoubleVar(self, name='txtVsys')
        txtPsys = self.txtPsys = DoubleVar(self, name='txtPsys')
        txtImp = self.txtImp = StringVar(self, name='txtImp')
        txtVmp = self.txtVmp = StringVar(self, name='txtVmp')
        txtPmp = self.txtPmp = StringVar(self, name='txtPmp')
        txtIsc = self.txtIsc = StringVar(self, name='txtIsc')
        txtVoc = self.txtVoc = StringVar(self, name='txtVoc')
        txtFF = self.txtFF = StringVar(self, name='txtFF')
        txtEff = self.txtEff = StringVar(self, name='txtEff')
        sysEe = self.sysEe = DoubleVar(self, 1, name='sysEe')
        txtImp.set("{:7.3f}".format(self.pvSys.Imp))  # [A]
        txtVmp.set("{:7.3f}".format(self.pvSys.Vmp))  # [V]
        txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000))  # [kW]
        txtIsc.set("{:7.3f}".format(self.pvSys.Isc))  # [A]
        txtVoc.set("{:7.3f}".format(self.pvSys.Voc))  # [V]
        txtFF.set("{:7.3f}".format(self.pvSys.FF * 100))  # [%]
        txtEff.set("{:7.3f}".format(self.pvSys.eff * 100))  # [%]
        self.msgtext = StringVar(self, READY_MSG, 'msgtext')

        # must register vcmd and invcmd as Tcl functions
        vcmd = (self.register(self.validateWidget),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        invcmd = (self.register(self.invalidWidget),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')

        # SP logo
        # convert image to tk-compatible format (.gif, .pgm, or .ppm)
        self.SPlogo = ImageTk.PhotoImage(Image.open(SPLOGO))
        # bg='black' fills extra space with black
        # anchor=W aligns photoimage on left side, NW is no different
        # padding is ignored by images, use borderwidth
        Label(self, image=self.SPlogo, borderwidth=5, bg='black',
              anchor=W).pack(fill=BOTH)
        # fill=BOTH expands the photoimage to fill parent frame
        # w/o fill=BOTH photoimage is centered in frame even with anchor=W
        # Intro text
        introText = 'PVmismatch calculates I-V and P-V curves as well as the'
        introText += ' max power point (MPP) for any sized system.\nSet the'
        introText += ' number of strings in the system, the number of modules'
        introText += ' per string and the number cells per module.'
        # anchor=W aligns message on left side, NW is no different
        # fg='white' sets text color to white, default is black, so it doesn't
        #   show on black background
        # default aspect is 150%, about as wide as high, or set width>0
        Message(self, text=introText, width=750, bg='black', fg='white',
                anchor=W).pack(fill=BOTH)
        # fill=BOTH expands the message to fill parent frame
        # w/o fill=BOTH message is centered in frame even with anchor=W

        # PVsystem frame
        pvSysFrame = self.pvSysFrame = Frame(master, name='pvSysFrame')
        # fill=BOTH keeps widgets in frame on left when window is resized
        pvSysFrame.pack(fill=BOTH)

        # PVsystem matplotlib figure canvas
        self.pvSysPlotFrame = Frame(pvSysFrame, name='pvSysPlotFrame')
        pvSysPlotFrame = self.pvSysPlotFrame
        pvSysPlotFrame.pack(side=RIGHT)
        pvSysPlot = self.pvSysPlot = pvSys.plotSys()
        self.pvSysFigCanvas = FigureCanvasTkAgg(pvSysPlot,
                                                master=pvSysPlotFrame,
                                                resize_callback=None)
        pvSysFigCanvas = self.pvSysFigCanvas
        pvSysFigCanvas.get_tk_widget()._name = 'pvSysFigCanvas'  # IGNORE:W0212
        pvSysFigCanvas.show()
        # NB: FigureCanvasTkAgg._tkcanvas is FigureCanvasTkAgg.get_tk_widget()
        pvSysFigCanvas.get_tk_widget().pack(fill=BOTH)
        pvSysToolbar = NavigationToolbar2TkAgg(pvSysFigCanvas, pvSysPlotFrame)
        pvSysToolbar.update()
        pvSysToolbar.pack(fill=BOTH)

        # PVsystem data frame
        pvSysDataFrame = self.pvSysDataFrame = Frame(pvSysFrame,
                                                     name='pvSysDataFrame')
        pvSysDataFrame.pack(side=LEFT)
        _row = 0
        Label(pvSysDataFrame,
              text='PVsystem', font=CAPTION_FONT).grid(row=_row, columnspan=3,
                                                     sticky=W)

        # number of strings
        _row += 1  # row 1
        Label(pvSysDataFrame,
              text='Number of Strings').grid(row=_row, columnspan=2, sticky=W)
        # use textVar to set number of strings from LOAD, RESET or default
        spinboxCnf = {'name': 'numStrSpinbox', 'from_': 1, 'to': MAX_STRINGS,
                      'textvariable': numStrs, 'width': 5, 'validate': 'all',
                      'validatecommand': vcmd, 'invalidcommand': invcmd,
                      'command': self.updatePVsys}
        self.numStrSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf)
        self.numStrSpinbox.bind("<Return>", self.keyBinding)
        self.numStrSpinbox.grid(row=_row, column=2)

        # number of modules
        _row += 1  # row 2
        Label(pvSysDataFrame,
              text='Number of Modules').grid(row=_row, columnspan=2, sticky=W)
        # number of modules spinbox
        spinboxCnf = {'name': 'numModSpinbox', 'from_': 1, 'to': MAX_MODULES,
                      'textvariable': numMods, 'width': 5, 'validate': 'all',
                      'validatecommand': vcmd, 'invalidcommand': invcmd,
                      'command': self.updatePVsys}
        self.numModSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf)
        self.numModSpinbox.bind("<Return>", self.keyBinding)
        self.numModSpinbox.grid(row=_row, column=2)

        # number of cells
        _row += 1  # row 3
        Label(pvSysDataFrame,
              text='Number of Cells').grid(row=_row, columnspan=2, sticky=W)
        # http://www.logilab.org/card/pylintfeatures#basic-checker
        # pylint: disable = W0142
        self.numCellOption = OptionMenu(pvSysDataFrame, numCells, *MODSIZES,
                                        command=self.updatePVsys)
        # pylint: enable = W0142
        self.numCellOption._name = 'numCellOption'  # IGNORE:W0212
        self.numCellOption.grid(row=_row, column=2)

        # Advanced Configuration button
        _row += 1  # row 14
        buttonCnf = {'name': 'advCnfButton', 'text': 'Advanced Configuration',
                     'command': self.startAdvCnf_tk}
        pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf)
        pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W))

        # slider to explore IV curves
        _row += 1  # row 4, 5 & 6
        self.pvSysScale = Scale(pvSysDataFrame, orient=HORIZONTAL,
                                label='I-V Curve', font=CAPTION_FONT,
                                command=self.getIV, showvalue=False,
                                from_=0, to=(pvSys.pvconst.npts - 1))
        self.pvSysScale.grid(row=_row, columnspan=3, sticky=(E + W))
        # Isys
        Label(pvSysDataFrame, text='Isys [A]').grid(row=(_row + 1))
        self.pvIsys = Entry(pvSysDataFrame, textvariable=txtIsys,
                            width=7)
        self.pvIsys.grid(row=(_row + 2))
        # Vsys
        Label(pvSysDataFrame, text='Vsys [V]').grid(row=(_row + 1), column=1)
        self.pvVsys = Entry(pvSysDataFrame, textvariable=txtVsys,
                            width=7)
        self.pvVsys.grid(row=(_row + 2), column=1)
        # Psys
        Label(pvSysDataFrame, text='Psys [kW]').grid(row=(_row + 1), column=2)
        self.pvPsys = Entry(pvSysDataFrame, textvariable=txtPsys,
                            width=7)
        self.pvPsys.grid(row=(_row + 2), column=2)

        # Imp, Vmp & Pmp
        _row += 3  # row 7, 8, 9, 10, 11 & 12
        Label(pvSysDataFrame,
              text='I-V Characteristics',
              font=CAPTION_FONT).grid(row=_row, columnspan=3, sticky=W)
        Label(pvSysDataFrame, text='Imp [A]').grid(row=(_row + 1))
        Label(pvSysDataFrame, text='Vmp [V]').grid(row=(_row + 1), column=1)
        Label(pvSysDataFrame, text='Pmp [kW]').grid(row=(_row + 1), column=2)
        self.pvImp = Entry(pvSysDataFrame, textvariable=txtImp,
                            width=7, state='readonly')
        self.pvImp.grid(row=(_row + 2))
        self.pvVmp = Entry(pvSysDataFrame, textvariable=txtVmp,
                            width=7, state='readonly')
        self.pvVmp.grid(row=(_row + 2), column=1)
        self.pvPmp = Entry(pvSysDataFrame, textvariable=txtPmp,
                            width=7, state='readonly')
        self.pvPmp.grid(row=(_row + 2), column=2)
        # Isc, Voc & FF
        Label(pvSysDataFrame, text='Isc [A]').grid(row=(_row + 3))
        Label(pvSysDataFrame, text='Voc [V]').grid(row=(_row + 3), column=1)
        Label(pvSysDataFrame, text='FF [%]').grid(row=(_row + 3), column=2)
        self.pvIsc = Entry(pvSysDataFrame, textvariable=txtIsc,
                            width=7, state='readonly')
        self.pvIsc.grid(row=(_row + 4))
        self.pvVoc = Entry(pvSysDataFrame, textvariable=txtVoc,
                            width=7, state='readonly')
        self.pvVoc.grid(row=(_row + 4), column=1)
        self.pvFF = Entry(pvSysDataFrame, textvariable=txtFF,
                            width=7, state='readonly')
        self.pvFF.grid(row=(_row + 4), column=2)
        Label(pvSysDataFrame, text='Efficiency [%]').grid(row=(_row + 5),
                                                          columnspan=2)
        self.pvEff = Entry(pvSysDataFrame, textvariable=txtEff,
                            width=7, state='readonly')
        self.pvEff.grid(row=(_row + 5), column=2)

        # set suns
        _row += 6  # row 13
        Label(pvSysDataFrame, text='Irradiance [suns]',
              font=CAPTION_FONT).grid(row=_row, columnspan=2, sticky=W)
        # number of modules spinbox
        spinboxCnf = {'name': 'sunSpinbox', 'from_': 0.2, 'to': MAX_SUNS,
                      'increment': 0.1, 'textvariable': sysEe, 'width': 5,
                      'validate': 'all', 'validatecommand': vcmd,
                      'invalidcommand': invcmd, 'command': self.updatePVsys}
        self.sunSpinbox = Spinbox(pvSysDataFrame, cnf=spinboxCnf)
        self.sunSpinbox.bind("<Return>", self.keyBinding)
        self.sunSpinbox.grid(row=_row, column=2)

        # PVstring button
        _row += 1  # row 14
        buttonCnf = {'name': 'pvStrButton', 'text': 'PVstring',
                     'command': self.startPVstring_tk}
        pvStrButton = self.pvStrButton = Button(pvSysDataFrame, buttonCnf)
        pvStrButton.grid(row=_row, columnspan=3, sticky=(E + W))

        # toolbar
        toolbar = self.toolbarframe = Frame(master, name='toolbar')
        toolbar.pack(fill=BOTH)
        self.QUIT = Button(toolbar, text='Quit', command=self._quit)
        self.QUIT.pack(side=RIGHT)
        self.SAVE = Button(toolbar, text='Save', command=self._save)
        self.SAVE.pack(side=RIGHT)
        self.LOAD = Button(toolbar, text='Load', command=self._load)
        self.LOAD.pack(side=RIGHT)
        self.RESET = Button(toolbar, text='Reset', command=self._reset)
        self.RESET.pack(side=RIGHT)
        self.UPDATE = Button(toolbar, text='Update', command=self._update)
        self.UPDATE.pack(side=RIGHT)
        self.HELP = Button(toolbar, text='Help', command=self._help)
        self.HELP.pack(side=RIGHT)
        self.MESSAGE = Message(toolbar, textvariable=self.msgtext,
                               width=500, fg='red')
        self.MESSAGE.pack(side=LEFT)

#    Validation substitutions
#    %d  Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or
#        textvariable validation.
#    %i  Index of char string to be inserted/deleted, if any, otherwise -1.
#    %P  The value of the spinbox should edition occur. If you are configuring
#        the spinbox widget to have a new textvariable, this will be the value
#        of that textvariable.
#    %s  The current value of spinbox before edition.
#    %S  The text string being inserted/deleted, if any. Otherwise it is an
#        empty string.
#    %v  The type of validation currently set.
#    %V  The type of validation that triggered the callback (key, focusin,
#        focusout, forced).
#    %W  The name of the spinbox widget.

# TODO: Fix these functions so that delete and overwrite work

    def validateWidget(self, *args):
        # W = Tkinter.W = 'w' is already used, so use W_ instead
        (d, i, P, s, S, v, V, W_) = args  # @UnusedVariable # IGNORE:W0612
        logging.debug("OnValidate: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}".format(*args))
        if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox":
            valType = INTEGERS
            valTest = lambda val: int(val)  # IGNORE:W0108
        elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox":
            valType = INTEGERS
            valTest = lambda val: int(val)  # IGNORE:W0108
        elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox":
            valType = FLOATS
            valTest = lambda val: float(val)  # IGNORE:W0108
        else:
            return False
        w = self.nametowidget(W_)
        w.config(validate=v)
        if S in valType:
            try:
                valTest(P)
            except ValueError:
                return False
            return True
        else:
            return False

    def invalidWidget(self, *args):
        (d, i, P, s, S, v, V, W_) = args  # @UnusedVariable # IGNORE:W0612
        logging.debug("OnInvalid: d={}, i={}, P={}, s={}, S={}, v={}, V={}, W={}".format(*args))
        if W_ == ".pvSysFrame.pvSysDataFrame.numStrSpinbox":
            errText = 'Invalid number of strings!'
        elif W_ == ".pvSysFrame.pvSysDataFrame.numModSpinbox":
            errText = 'Invalid number of modules!'
        elif W_ == ".pvSysFrame.pvSysDataFrame.sunSpinbox":
            errText = 'Invalid irradiance!'
        else:
            errText = 'Unknown widget!'
        w = self.nametowidget(W_)
        w.config(validate=v)
        self.msgtext.set(errText)
        self.bell()

    def getIV(self, *args):
        logging.debug('args:\n\t%r', args)
        x = np.float64(float(args[0]) / self.pvSys.pvconst.npts / 2.)
        xp = np.concatenate((self.pvSys.pvconst.negpts, self.pvSys.pvconst.pts),
                            axis=0).flatten()
        Vsys = np.interp(x, xp, self.pvSys.Vsys)
        Isys = np.interp(x, xp, self.pvSys.Isys)
        Psys = Vsys * Isys / 1000
        self.txtVsys.set("{:7.3f}".format(Vsys))
        self.txtIsys.set("{:7.3f}".format(Isys))
        self.txtPsys.set("{:7.3f}".format(Psys))

    def startPVstring_tk(self):
        top = Toplevel()
        app = PVstring_tk(self, top)
        app.mainloop()
        # please destroy me or I'll continue to run in background
        top.destroy()

    def startAdvCnf_tk(self):
        """
        open advnaced config window
        """
        top = Toplevel(name='advCnfTop')
        app = AdvCnf_tk(self, top)
        app.mainloop()
        # please destroy me or I'll continue to run in background
        top.destroy()

    def keyBinding(self, event):
        logging.debug('event widget:\n\t%r', event.widget)
        logging.debug('event widget get:\n\t%r', event.widget.get())
        self.updatePVsys()

    def updatePVsys(self, *args, **kwargs):
        logging.debug('args:\n\t%r', args)
        logging.debug('kwargs:\n\t%r', kwargs)
        if args and isinstance(args[0], PVsystem_cls):
            pvsys = args[0]
            for n, pvstr in enumerate(pvsys.pvstrs):
                for pvmod in pvstr.pvmods:
                    pvmod.calcMod()
                pvstr.calcString()
                logging.debug('updating pvstring #%d: Pmp = %g[W]', n, pvstr.Pstring.max())
            return
        PVAPP = "pvapplication"
        try:
            numStrs = self.numStrs.get()
            if not (0 < numStrs <= self.validationConstants[PVAPP]["numStrs"]):
                raise PVValidationError('numStrs', numStrs)
            numMods = self.numMods.get()
            if not (0 < numMods <= self.validationConstants[PVAPP]["numMods"]):
                raise PVValidationError('numMods', numMods)
            sysEe = self.sysEe.get()
            if not (0 < sysEe <= self.validationConstants[PVAPP]["sysEe"]):
                raise PVValidationError('sysEe', sysEe)
        except PVValidationError as err:
            logging.debug('err:\n\t%r', err)
            errtext = self.messagetext[PVAPP][err.argname]
            self.msgtext.set(errtext)
            self.bell()
            return
        numCells = self.numCells.get()
        self.msgtext.set(self.messagetext[PVAPP]["Ready"])
        pvconst = self.pvSys.pvconst
        pvcell = PVcell(Ee=sysEe)
        if numCells == 24:
            numCells = STD24
        elif numCells == 72:
            numCells = STD72
        elif numCells == 96:
            numCells = STD96
        elif numCells == 128:
            numCells = STD128
        pvmods = PVmodule(cell_pos=numCells, pvcells=pvcell)
        self.pvSys = PVsystem(pvconst, numStrs, numberMods=numMods,
                              pvmods=pvmods)
        self.updateIVstats()


    def updateIVstats(self):
        # reuse sysPlot figure and update pvSysFigCanvas
        self.pvSysPlot = self.pvSys.plotSys(self.pvSysPlot)
        self.pvSysFigCanvas.show()
        self.txtImp.set("{:7.3f}".format(self.pvSys.Imp))  # [A]
        self.txtVmp.set("{:7.3f}".format(self.pvSys.Vmp))  # [V]
        self.txtPmp.set("{:7.3f}".format(self.pvSys.Pmp / 1000))  # [kW]
        self.txtIsc.set("{:7.3f}".format(self.pvSys.Isc))  # [A]
        self.txtVoc.set("{:7.3f}".format(self.pvSys.Voc))  # [V]
        self.txtFF.set("{:7.3f}".format(self.pvSys.FF * 100))  # [%]
        self.txtEff.set("{:7.3f}".format(self.pvSys.eff * 100))  # [%]

    def _help(self):
        logging.debug('show docs in browser')
        webbrowser.open(DOCS)

    def _update(self):
        self.msgtext.set(READY_MSG)
        self.updatePVsys()

    def _reset(self):
        # number of strings integer variable
        self.numStrs.set(NUMBERSTRS)  # default
        # number of modules integer variable
        self.numMods.set(NUMBERMODS)  # default
        # number of cells integer variable
        self.numCells.set(NUMBERCELLS)  # default value is 96
        self.msgtext.set(READY_MSG)
        # TODO: need to reset advCnf too
        logging.debug('reset')

    def _load(self):
        logging.debug('load *.pv file')

    def _save(self):
        logging.debug('save *.pv file')

    def _quit(self):
        # this is necessary on Windows to prevent
        # Fatal Python Error: PyEval_RestoreThread: NULL tstate
        self.master.quit()  # stops mainloop
        self.master.destroy()

    def readJSON(self, JSONfilename):
        if not JSONfilename.endswith('json'):
            JSONfilename += '.json'
        JSONfullpath = os.path.join(JSONDIR, JSONfilename)
        with open(JSONfullpath, 'r') as JSONfile:
            JSONObjects = json.load(JSONfile)
            logging.debug('JSON objects loaded from %s.', JSONfullpath)
        return JSONObjects
class NavigationForTableFrame(Frame):
    ''' This class is responsible for navigation over the table object.
        Table rows are displayed page by page.
        This class provides buttons that allow to navigate from page
        to page.

        Attributes:
            table (TableFrame or any object that has attribute nb_rows and
                implements display_data method): table that should be navigated.
            goto_spin (Spinbox): Spinbox widget that allows to enter page
                number and to switch between pages.
            text_var_nb_pages (StringVar): text variable that shows total
                number of pages.
            current_page_str (StringVar): text variable that stores
                currently displayed page.

        Args:
            parent (Tk object): parent for this frame.
            table (TableFrameWithInputOutputBox): table with multiple pages that
                will be navigated by this frame.
    '''
    def __init__(self, parent, table, *args, **kw):
        super().__init__(parent, *args, **kw)
        self.table = table
        self.goto_spin = None
        self.text_var_nb_pages = StringVar()
        self.current_page_str = StringVar()
        self.create_widgets()

    def create_widgets(self):
        ''' Creates all necessary widgets for navigation.
        '''
        prev_btn = Button(self, text='<<', width=5,
                          command=self.show_prev_page)
        prev_btn.grid(row=0, column=0, sticky=N, padx=3)
        next_btn = Button(self, text='>>', width=5,
                          command=self.show_next_page)
        next_btn.grid(row=0, column=1, sticky=N)
        goto_lbl = Label(self, text='Go to')
        goto_lbl.grid(row=0, column=3, sticky=N, padx=5)

        self.goto_spin = Spinbox(self, width=7, from_=1, to=1,
                                 textvariable=self.current_page_str,
                                 command=self.on_page_change)

        self.goto_spin.bind('<Return>', self.on_page_change)
        self.goto_spin.grid(row=0, column=4, sticky=N, padx=5)
        nb_pages_lb = Label(self, textvariable=self.text_var_nb_pages)
        nb_pages_lb.grid(row=0, column=5, sticky=W+N, padx=5)
        self.reset_navigation()

    def show_prev_page(self):
        ''' Displays previous page.

            This method is called when user presses button '<<'.
            If the first page is currently displayed and the method is called,
            then the call to this method is ignored.
        '''
        prev_page_index = int(self.current_page_str.get()) - 1
        if prev_page_index > 0:
            self.current_page_str.set(prev_page_index)
            self.on_page_change()

    def show_next_page(self):
        ''' Displays next page.

            This method is called when user presses button '>>'.
            If the last page is currently displayed and the method is called,
            then the call to this method is ignored.
        '''
        next_page_index = int(self.current_page_str.get()) + 1
        if next_page_index <= int(self.goto_spin.cget('to')):
            self.current_page_str.set(next_page_index)
            self.on_page_change()

    def on_page_change(self, *args):
        ''' Displays a page which number is currently stored in
            current_page_str.

            This method is called in show_next_page(), show_prev_page() and
            when the user enters data and presses Enter.
            args are supplied by Return event.
            If the entered value is invalid, then the first page is displayed.
            If the entered value is zero or negative, then the first page is
            isplayed.
            If the entered value is larger than the total number of pages,
            then the last page is displayed.
        '''
        try:
            curr_page = int(self.current_page_str.get())
        except ValueError:
            curr_page = 1
            self.current_page_str.set(curr_page)

        max_page = int(self.goto_spin.cget('to'))
        if curr_page > max_page:
            curr_page = max_page
            self.current_page_str.set(curr_page)
        if curr_page <= 0:
            curr_page = 1
            self.current_page_str.set(curr_page)
        # second -1 because row indeces start with 0
        row_index = calculate_start_row_index(curr_page, self.table.nb_rows)

        self.table.display_data(row_index)

    def reset_navigation(self):
        ''' Resets navigation parameters.

            Sets current page number to 1 and total number of pages to zero.
        '''
        self.current_page_str.set('1')
        self.text_var_nb_pages.set('1 pages')
        self.goto_spin.config(to=1)

    def set_navigation(self, nb_data_pages, reset_curr_page=True):
        ''' Sets navigation parameters.

            Sets current page number to 1 and total number of pages
            to nb_data_pages.

            Args:
                nb_data_pages (int): new value for the total number of pages.
                reset_curr_page (bool): True is current page must be reset to 1,
                    False otherwise.
        '''
        self.goto_spin.config(to=nb_data_pages)
        if reset_curr_page:
            self.current_page_str.set('1')
        self.text_var_nb_pages.set('{0} pages'.format(nb_data_pages))
Esempio n. 16
0
    def __init__(self, app):
        info(' - initializing module: Spectrogram')

        self.app = app

        self.frame = Frame(self.app.BOTTOM)
        self.frame.grid(row=0,
                        column=1,
                        pady=(self.app.pady * 2, self.app.pady / 2))
        self.axis_frame = Frame(self.app.BOTTOM)
        self.axis_frame.grid(row=0,
                             column=0,
                             sticky='e',
                             pady=(self.app.pady * 2, self.app.pady / 2))
        self.canvas_width = self.app.TextGrid.canvas_width
        self.canvas_height = 106
        self.canvas = Canvas(self.frame,
                             width=self.canvas_width,
                             height=self.canvas_height,
                             background='gray',
                             highlightthickness=0)
        self.spectrogram = None
        self.spec_freq_max = DoubleVar()
        self.wl = DoubleVar()
        self.dyn_range = DoubleVar()
        self.clicktime = -1
        self.specClick = False
        self.oldSelected = None
        self.doDefaults()

        #make spinboxes & buttons for spectrogram specs
        self.spinwin = Frame(self.axis_frame)
        #spinboxes
        axis_ceil_box = Spinbox(self.spinwin,
                                textvariable=self.spec_freq_max,
                                command=self.drawSpectrogram,
                                width=7,
                                increment=100,
                                from_=0,
                                to_=100000)
        axis_ceil_box.bind('<Return>', self.drawSpectrogram)
        axis_ceil_box.bind('<Escape>', lambda ev: self.spinwin.focus())
        wl_box = Spinbox(self.spinwin,
                         textvariable=self.wl,
                         command=self.drawSpectrogram,
                         width=7,
                         increment=0.0005,
                         from_=0,
                         to_=1)
        wl_box.bind('<Return>', self.drawSpectrogram)
        wl_box.bind('<Escape>', lambda ev: self.spinwin.focus())
        dyn_range_box = Spinbox(self.spinwin,
                                textvariable=self.dyn_range,
                                command=self.drawSpectrogram,
                                width=7,
                                increment=10,
                                from_=0,
                                to_=10000)
        dyn_range_box.bind('<Return>', self.drawSpectrogram)
        dyn_range_box.bind('<Escape>', lambda ev: self.spinwin.focus())
        #buttons
        default_btn = Button(self.spinwin,
                             text='Standards',
                             command=self.restoreDefaults,
                             takefocus=0)
        apply_btn = Button(self.spinwin,
                           text='Apply',
                           command=self.drawSpectrogram,
                           takefocus=0)

        # self.axis_frame.create_window(wwidth,self.canvas_height, window=self.spinwin, anchor='ne')
        #grid spinboxes & buttons on subframe
        axis_ceil_box.grid(row=0, columnspan=2, sticky='ne')
        wl_box.grid(row=1, columnspan=2, sticky='ne')
        dyn_range_box.grid(row=2, columnspan=2, sticky='ne')
        default_btn.grid(row=3)
        apply_btn.grid(row=3, column=1)

        self.grid()

        self.canvas.bind('<Button-1>', self.jumpToFrame)
Esempio n. 17
0

def scr_leave(event):
    scr['bg'] = 'white'


def spin_hover(event):
    spin['bg'] = 'gray94'


def spin_leave(event):
    spin['bg'] = 'white'


scr.bind('<Enter>', scr_hover)
scr.bind('<Leave>', scr_leave)

spin.bind('<Enter>', spin_hover)
spin.bind('<Leave>', spin_leave)

# String Formatting
# name = 'John'
# print('Hello, %s!' % name)
# %d integers
# %s string
# %f decimals
# %.<number of digits>f


gui.mainloop()
Esempio n. 18
0
class Settings_for_root(Frame):
    def __init__(self, master, board, writer, background, dimensions,
                 transparency):
        super().__init__(master, bg='#435661')

        self.master = master
        self.board = board
        self.writer = writer
        self.width = None
        self.height = None
        self.xoff = None
        self.yoff = None
        self.transparency = None
        self.entry = None
        self.current_dim = None
        self.apply = None
        self.confirm = None

        self.set_layout(background, dimensions, transparency)

    def set_layout(self, background, dimensions, transparency):
        w, h, x, y = dimensions

        self.width = Spinbox(self,
                             background='#defffc',
                             foreground='#435661',
                             from_=0,
                             to_=10000,
                             justify='center',
                             highlightthickness=0,
                             increment=1,
                             command=self._apply)
        self.width.place(relx=0.0725,
                         rely=0.075,
                         relwidth=0.3325,
                         relheight=0.0325,
                         anchor='nw')

        self.height = Spinbox(self,
                              background='#defffc',
                              foreground='#435661',
                              from_=0,
                              to_=10000,
                              justify='center',
                              highlightthickness=0,
                              increment=1,
                              command=self._apply)
        self.height.place(relx=0.5825,
                          rely=0.075,
                          relwidth=0.3425,
                          relheight=0.033,
                          anchor='nw')

        self.xoff = Spinbox(self,
                            background='#defffc',
                            foreground='#435661',
                            from_=0,
                            to_=10000,
                            justify='center',
                            highlightthickness=0,
                            increment=1,
                            command=self._apply)
        self.xoff.place(relx=0.069,
                        rely=0.186,
                        relwidth=0.333,
                        relheight=0.0325,
                        anchor='nw')

        self.yoff = Spinbox(self,
                            background='#defffc',
                            foreground='#435661',
                            from_=0,
                            to_=10000,
                            justify='center',
                            highlightthickness=0,
                            increment=1,
                            command=self._apply)
        self.yoff.place(relx=0.582,
                        rely=0.186,
                        relwidth=0.343,
                        relheight=0.033,
                        anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='width') \
            .place(relx=0.103, rely=0.048, relwidth=0.27, relheight=0.0275, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='height') \
            .place(relx=0.63, rely=0.05, relwidth=0.25, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='x offset') \
            .place(relx=0.135, rely=0.161, relwidth=0.2025, relheight=0.025, anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='y offset') \
            .place(relx=0.635, rely=0.16, relwidth=0.23, relheight=0.02625, anchor='nw')

        self.current_dim = myButton(self,
                                    text="Set current root's dimensions",
                                    command=lambda *args: self.set_current())
        self.current_dim.place(relx=0.175,
                               rely=0.2537,
                               relwidth=0.65,
                               relheight=0.035,
                               anchor='nw')

        self.transparency = Spinbox(self,
                                    background='#defffc',
                                    foreground='#435661',
                                    from_=0,
                                    to_=1,
                                    justify='center',
                                    highlightthickness=0,
                                    increment=0.01,
                                    command=self._apply)
        self.transparency.place(relx=0.3,
                                rely=0.36,
                                relwidth=0.4,
                                relheight=0.03375,
                                anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='transparency') \
            .place(relx=0.324, rely=0.335, relwidth=0.34, relheight=0.025, anchor='nw')

        self.entry = Entry(self,
                           borderwidth=0,
                           background='#557282',
                           foreground='#defffc',
                           highlightthickness=0,
                           justify="center")
        self.entry.place(relx=0.3,
                         rely=0.4725,
                         relwidth=0.4,
                         relheight=0.04625,
                         anchor='nw')

        Label(self, background='#435661', foreground='#defffc', text='background') \
            .place(relx=0.375, rely=0.449, relwidth=0.2525, relheight=0.02375, anchor='nw')

        self.apply = myButton(self,
                              text="Apply",
                              command=lambda *args: self._apply())
        self.apply.place(relx=0.23,
                         rely=0.6075,
                         relwidth=0.54,
                         relheight=0.05125,
                         anchor='nw')

        self.confirm = myButton(self,
                                text="CONFIRM",
                                command=lambda *args: self._confirm())
        self.confirm.place(relx=0.23,
                           rely=0.7762,
                           relwidth=0.54,
                           relheight=0.09125,
                           anchor='nw')

        self.width.delete(0, "end")
        self.height.delete(0, "end")
        self.xoff.delete(0, "end")
        self.yoff.delete(0, "end")
        self.width.insert("end", w)
        self.height.insert("end", h)
        self.xoff.insert("end", x)
        self.yoff.insert("end", y)

        self.transparency.delete(0, "end")
        self.transparency.insert("end", transparency)

        self.width.bind("<Return>", lambda *args: self._apply())
        self.height.bind("<Return>", lambda *args: self._apply())
        self.xoff.bind("<Return>", lambda *args: self._apply())
        self.yoff.bind("<Return>", lambda *args: self._apply())
        self.transparency.bind("<Return>", lambda *args: self._apply())

        self.entry.insert("end", background)

    def set_current(self):
        w, h = self.board.winfo_width(), self.board.winfo_height()
        x, y = self.board.master.winfo_x(), self.board.master.winfo_y()

        self.width.delete(0, "end")
        self.height.delete(0, "end")
        self.xoff.delete(0, "end")
        self.yoff.delete(0, "end")
        self.width.insert("end", w)
        self.height.insert("end", h)
        self.xoff.insert("end", x)
        self.yoff.insert("end", y)

    def _apply(self):
        self.board.configure(bg=self.entry.get())

        w = self.width.get()
        h = self.height.get()
        x = self.xoff.get()
        y = self.yoff.get()
        self.board.master.geometry(f"{w}x{h}+{x}+{y}")

        self.board.master.attributes("-alpha", self.transparency.get())

    def _confirm(self):
        self.board.configure(bg=self.entry.get())
        self.writer.app_background = self.entry.get()

        w = self.width.get()
        h = self.height.get()
        x = self.xoff.get()
        y = self.yoff.get()
        self.board.master.geometry(f"{w}x{h}+{x}+{y}")

        self.writer.app_geometry = f"{w}x{h}+{x}+{y}"
        self.writer.app_transparency = self.transparency.get()

        self.destroy()
Esempio n. 19
0
class NavigationForTableFrame(Frame):
    ''' This class is responsible for navigation over the table object.
        Table rows are displayed page by page.
        This class provides buttons that allow to navigate from page
        to page.

        Attributes:
            table (TableFrame or any object that has attribute nb_rows and
                implements display_data method): table that should be navigated.
            goto_spin (Spinbox): Spinbox widget that allows to enter page
                number and to switch between pages.
            text_var_nb_pages (StringVar): text variable that shows total
                number of pages.
            current_page_str (StringVar): text variable that stores
                currently displayed page.

        Args:
            parent (Tk object): parent for this frame.
            table (TableFrameWithInputOutputBox): table with multiple pages that
                will be navigated by this frame.
    '''
    def __init__(self, parent, table, *args, **kw):
        super().__init__(parent, *args, **kw)
        self.table = table
        self.goto_spin = None
        self.text_var_nb_pages = StringVar()
        self.current_page_str = StringVar()
        self.create_widgets()

    def create_widgets(self):
        ''' Creates all necessary widgets for navigation.
        '''
        prev_btn = Button(self,
                          text='<<',
                          width=5,
                          command=self.show_prev_page)
        prev_btn.grid(row=0, column=0, sticky=N, padx=3)
        next_btn = Button(self,
                          text='>>',
                          width=5,
                          command=self.show_next_page)
        next_btn.grid(row=0, column=1, sticky=N)
        goto_lbl = Label(self, text='Go to')
        goto_lbl.grid(row=0, column=3, sticky=N, padx=5)

        self.goto_spin = Spinbox(self,
                                 width=7,
                                 from_=1,
                                 to=1,
                                 textvariable=self.current_page_str,
                                 command=self.on_page_change)

        self.goto_spin.bind('<Return>', self.on_page_change)
        self.goto_spin.grid(row=0, column=4, sticky=N, padx=5)
        nb_pages_lb = Label(self, textvariable=self.text_var_nb_pages)
        nb_pages_lb.grid(row=0, column=5, sticky=W + N, padx=5)
        self.reset_navigation()

    def show_prev_page(self):
        ''' Displays previous page.

            This method is called when user presses button '<<'.
            If the first page is currently displayed and the method is called,
            then the call to this method is ignored.
        '''
        prev_page_index = int(self.current_page_str.get()) - 1
        if prev_page_index > 0:
            self.current_page_str.set(prev_page_index)
            self.on_page_change()

    def show_next_page(self):
        ''' Displays next page.

            This method is called when user presses button '>>'.
            If the last page is currently displayed and the method is called,
            then the call to this method is ignored.
        '''
        next_page_index = int(self.current_page_str.get()) + 1
        if next_page_index <= int(self.goto_spin.cget('to')):
            self.current_page_str.set(next_page_index)
            self.on_page_change()

    def on_page_change(self, *args):
        ''' Displays a page which number is currently stored in
            current_page_str.

            This method is called in show_next_page(), show_prev_page() and
            when the user enters data and presses Enter.
            args are supplied by Return event.
            If the entered value is invalid, then the first page is displayed.
            If the entered value is zero or negative, then the first page is
            isplayed.
            If the entered value is larger than the total number of pages,
            then the last page is displayed.
        '''
        try:
            curr_page = int(self.current_page_str.get())
        except ValueError:
            curr_page = 1
            self.current_page_str.set(curr_page)

        max_page = int(self.goto_spin.cget('to'))
        if curr_page > max_page:
            curr_page = max_page
            self.current_page_str.set(curr_page)
        if curr_page <= 0:
            curr_page = 1
            self.current_page_str.set(curr_page)
        # second -1 because row indeces start with 0
        row_index = calculate_start_row_index(curr_page, self.table.nb_rows)

        self.table.display_data(row_index)

    def reset_navigation(self):
        ''' Resets navigation parameters.

            Sets current page number to 1 and total number of pages to zero.
        '''
        self.current_page_str.set('1')
        self.text_var_nb_pages.set('1 pages')
        self.goto_spin.config(to=1)

    def set_navigation(self, nb_data_pages, reset_curr_page=True):
        ''' Sets navigation parameters.

            Sets current page number to 1 and total number of pages
            to nb_data_pages.

            Args:
                nb_data_pages (int): new value for the total number of pages.
                reset_curr_page (bool): True is current page must be reset to 1,
                    False otherwise.
        '''
        self.goto_spin.config(to=nb_data_pages)
        if reset_curr_page:
            self.current_page_str.set('1')
        self.text_var_nb_pages.set('{0} pages'.format(nb_data_pages))