Ejemplo n.º 1
1
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                style='Custom.Treeview', height=REPORT_HEIGHT,
                                yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(8)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        summ = 0
        for item in iterator:

            value = item.quantity * item.price * (100 - item.discount) / 100
            summ += value

            col = []
            col.append(add_s(item.check.id))
            col.append(add_s(item.goods.cathegory.name))
            col.append(add_s(item.goods.name))
            col.append(add_s(item.quantity))
            col.append(add_s(item.discount) +'%' if item.discount else ' -- ')
            col.append(add_s(u'%6.2f грн.' % value))
            col.append(add_s(item.check.date_time.strftime('%d.%m.%Y')))
            col.append(add_s(item.check.date_time.time())[:8])

            flag = not flag
            if flag:
                tree.insert('', 'end', text='', values=col, tag='2')
            else:
                tree.insert('', 'end', text='', values=col, tag='1')

        return summ
Ejemplo n.º 2
0
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                    style='Custom.Treeview', height=REPORT_HEIGHT,
                                    yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(7)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        for item in iterator:
            col = []
            col.append(add_s(item.goods.cathegory.name if item.goods.cathegory
                                                                 else u'-Нет-'))
            col.append(add_s(item.goods.name))
            col.append(add_s(item.quantity))
            col.append(add_s(item.goods.measure))
            col.append(add_s(item.date_time.strftime('%d.%m.%Y')))
            col.append(add_s(item.reason.reason))
            col.append(form(item.full_reason))

            flag = not flag
            if flag:
                tree.insert('', 'end', text='', values=col, tag='2')
            else:
                tree.insert('', 'end', text='', values=col, tag='1')
Ejemplo n.º 3
0
class MainWindow(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.treeview = None
        self.createui()
        self.loadtable()
        self.grid(sticky=(N, S, W, E))
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_columnconfigure(0, weight=1)

    def createui(self):
        image = Image.open('header.png')
        photo = ImageTk.PhotoImage(image)
        lbl = Label(self, image=photo)
        lbl.image = photo
        lbl.grid(row=0, column=0, columnspan=2, sticky='ns')
        self.treeview = Treeview(self)
        self.treeview['columns'] = ['title']
        self.treeview.heading("#0", text='Repeticiones', anchor='center')
        self.treeview.column("#0", anchor="center", width=90)
        self.treeview.heading('title', text='Titulo', anchor='w')
        self.treeview.column('title', anchor='w', width=700)
        self.treeview.grid(sticky=(N, S, W, E))
        self.treeview.bind("<Double-1>", self.openlink)
        ysb = Scrollbar(self, width=18, orient='vertical', command=self.treeview.yview)
        ysb.grid(row=1, column=1, sticky='ns')
        self.treeview.configure(yscroll=ysb.set)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

    def openlink(self, event):
        item = self.treeview.identify('item', event.x, event.y)
        web = self.treeview.item(item, 'values')[1]
        webbrowser.open_new(web)

    def loadtable(self):
        self.treeview.delete(*self.treeview.get_children())
        sorted_x = sorted(dic.items(), key=lambda x: x[1][1], reverse=True)
        for key, value in sorted_x:
            self.treeview.insert('', 'end', text=str(value[1]), values=[value[0], key])
Ejemplo n.º 4
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        #INSTANCIAS
        global cc, nombre, pago, ref, cod, desc, valor, resultado, total, tiempo, mes, anio, fechapago
        #INSTANCIAS DE LOS WIDGETS
        global e1, e2, e3, e4, e5, tree, l8, lb

        cc = IntVar()
        nombre = StringVar()
        pago = StringVar()
        ref = StringVar()
        cod = StringVar()
        desc = StringVar()
        valor = DoubleVar()

        tiempo = datetime.date.today()
        anio = time.strftime("%Y")
        mes = time.strftime("%B")
        fechapago = StringVar()

        total = 0.0
        resultado = DoubleVar()

        tbancos = [
            'Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"
        ]

        lupa = PhotoImage(file='img/lupa.png')

        tbanktype = ['Corriente', 'Ahorro']
        fpago = ['Efectivo', 'Transferencia']

        #BUSQUEDA = ["Nombre","CC/Nit"]
        busqueda = StringVar()
        busqueda.trace("w", lambda name, index, mode: buscar())
        dato = StringVar()

        #WIDGETS

        #========================= HEADER ==============================

        self.titleL = Label(self, text="GASTOS", font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #========================== WRAPPER ============================

        self.wrapper = Frame(self)
        self.wrapper.pack(side=LEFT, fill=Y)
        #Esto centro el wrapper
        #self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)

        #======================== BENEFICIARIO =======================

        self.lf1 = LabelFrame(self.wrapper, text="Beneficiario")
        self.lf1.pack(fill=X, ipady=5)

        self.f0 = Frame(self.lf1)
        self.f0.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(self.f0, text='CC/Nit:')
        l1.pack(side=LEFT)

        e1 = Entry(self.f0, textvariable=cc)
        e1.pack(side=LEFT)
        e1.bind('<Return>', buscarB)

        b0 = Button(self.f0,
                    text='Buscar:',
                    image=lupa,
                    command=topBeneficiarios)
        b0.pack(side=LEFT)

        l2 = Label(self.f0, text='Nombre:')
        l2.pack(side=LEFT)
        e2 = Entry(self.f0, textvariable=nombre)
        e2.pack(side=LEFT, fill=X, expand=1)

        self.f1 = Frame(self.lf1)
        self.f1.pack(pady=5, fill=X)  #-----------------------------------

        l3 = Label(self.f1, text='Forma de Pago:')
        l3.pack(side=LEFT)
        Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15)
        Cbx.set('Efectivo')
        Cbx.pack(side=LEFT)

        l4 = Label(self.f1, text='Ref. Bancaria:')
        l4.pack(side=LEFT)
        e3 = Entry(self.f1, textvariable=ref)
        e3.pack(side=LEFT, fill=X, expand=1)

        b1 = Button(self.f1, text='Buscar:', image=lupa)
        b1.image = lupa
        b1.pack(side=LEFT)

        #======================== CONCEPTO ========================

        self.lf2 = LabelFrame(self.wrapper, text="Concepto")
        self.lf2.pack(fill=X, ipady=5)

        self.f2 = Frame(self.lf2)
        self.f2.pack(pady=5, fill=X)  #-------------------------------

        l5 = Label(self.f2, text='Código:')
        l5.pack(side=LEFT)
        e4 = Entry(self.f2, textvariable=cod)
        e4.pack(side=LEFT)
        e4.bind('<Return>', buscarC)

        b2 = Button(self.f2,
                    text='Buscar:',
                    image=lupa,
                    command=topCtasContables)
        b2.pack(side=LEFT)

        self.f3 = Frame(self.lf2)
        self.f3.pack(pady=5, fill=X)  #-------------------------------

        l6 = Label(self.f3, text='Descripción:')
        l6.pack(side=LEFT)
        e5 = Entry(self.f3, textvariable=desc, state=DISABLED)
        e5.pack(side=LEFT, fill=X, expand=1)

        l7 = Label(self.f3, text='Valor:')
        l7.pack(side=LEFT)
        e6 = Entry(self.f3, width=15, textvariable=valor)
        e6.pack(side=LEFT)

        b3 = Button(self.f3, text='Agregar:', command=agregar)
        b3.pack(side=LEFT)

        #-------------------------- TREEVIEW ---------------------------

        self.f4 = Frame(self.wrapper)
        self.f4.pack(pady=5, fill=X)

        tree = Treeview(self.f4,
                        height=4,
                        show="headings",
                        columns=('col1', 'col2', 'col3'))
        tree.pack(side=LEFT, fill=X, expand=1)
        tree.column('col1', width=20, anchor='center')
        tree.column('col2', width=200, anchor='center')
        tree.column('col3', width=10, anchor='center')

        tree.heading('col1', text='Código')
        tree.heading('col2', text='Concepto')
        tree.heading('col3', text='Valor')

        scroll = Scrollbar(self.f4, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)
        tree.bind("<Delete>", borrar)

        #-------------------------- RESULTADOS ---------------------------

        self.f5 = Frame(self.wrapper)
        self.f5.pack(pady=5, fill=X)  #-------------------

        l8 = Label(self.f5,
                   textvariable=resultado,
                   fg="red",
                   bg="white",
                   anchor='e',
                   font="bold, 22",
                   relief=SUNKEN)
        l8.pack(fill=X, side=RIGHT, expand=1)

        #-------------------------- FOOTER ---------------------------

        self.fBtn = Frame(self.wrapper)
        self.fBtn.pack()  #-------------------------------

        clean = Button(self.fBtn,
                       text='Cancelar',
                       bg='navy',
                       foreground='white',
                       activebackground='red3',
                       activeforeground='white',
                       command=limpiar)
        clean.pack(side=RIGHT)

        add = Button(self.fBtn,
                     text='Grabar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=grabar)
        add.pack(side=RIGHT)

        #========================= ASIDE ===========================

        self.aside = Frame(self)
        self.aside.pack(side=TOP, fill=BOTH)

        self.wrap1 = Frame(self.aside)
        self.wrap1.pack()

        self.viewer = Label(self.wrap1, text="LISTA DE GASTOS")
        self.viewer.pack()

        scroll = Scrollbar(self.wrap1, orient=VERTICAL)
        scroll.pack(side=RIGHT, fill=Y)

        lb = Listbox(self.wrap1,
                     yscrollcommand=scroll.set,
                     height=20,
                     width=30)
        scroll.config(command=lb.yview)
        lb.pack(fill=BOTH)

        self.wrap2 = Frame(self.aside)
        self.wrap2.pack()

        load = Button(self.wrap2,
                      text='Cargar lista',
                      bg='navy',
                      foreground='white',
                      activebackground='red3',
                      activeforeground='white',
                      command=cargar_lista)
        load.pack(fill=X)

        delete = Button(self.wrap2,
                        text='Borrar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=None)
        delete.pack(fill=X)

        edit = Button(self.wrap2,
                      text='Modificar',
                      bg='navy',
                      foreground='white',
                      activebackground='red3',
                      activeforeground='white',
                      command=None)
        edit.pack(fill=X)

        buscador = Label(self.wrap2, text="Buscar por Número:")
        buscador.pack()
        E = Entry(self.wrap2, textvariable=busqueda, width=24)
        E.pack()
        E.bind("<KeyRelease>", caps)
Ejemplo n.º 5
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global e0, e1, e2, e3, e4, e5, e6, e7, e8, CbxVlr, observaciones, scroll, tree, pdfB, add
        global cc, arrend, inmueble, codigo, tel, valor
        global Cbx, meses, mes1, mes2, tiempo, fechapago, anio, mes
        global prop, nit, tp, subtotal, iva, total

        #VARIABLES
        tiempo = datetime.date.today()
        anio = time.strftime("%Y")
        mes = time.strftime("%B")
        fechapago = StringVar()

        cc = StringVar()
        arrend = StringVar()

        inmueble = StringVar()
        codigo = StringVar()
        tel = StringVar()
        valor = DoubleVar()

        prop = StringVar()
        nit = StringVar()
        tp = StringVar()

        subtotal = DoubleVar()
        iva = DoubleVar()
        total = DoubleVar()

        mes1 = StringVar()
        mes2 = StringVar()
        meses = [
            "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
            "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
        ]

        #WIDGETS

        #=========================== HEADER ============================

        self.titleL = Label(self, text="FACTURA INQUILINO", font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #========================= WRAPPER 1 ===========================

        wrapper = Frame(self)
        wrapper.pack(fill='both')

        #======================= DATOS GENERALES =======================

        self.lf = LabelFrame(wrapper, text="Datos generales")
        self.lf.pack(side=LEFT)  #-------------------------------

        self.f0 = Frame(self.lf)
        self.f0.pack(pady=5, fill=X)  #---------------------------

        self.ccnitL = Label(self.f0, text='CC/Nit:')
        self.ccnitL.pack(side=LEFT)
        e0 = Entry(self.f0, textvariable=cc, width=30)
        e0.pack(side=LEFT)

        self.b1 = Button(self.f0, text='Buscar', command=buscar)
        self.b1.pack(side=LEFT)

        self.f1 = Frame(self.lf)
        self.f1.pack(pady=5, fill=X)  #---------------------------

        self.nombreL = Label(self.f1, text='Nombre:')
        self.nombreL.pack(side=LEFT)
        e1 = Entry(self.f1, textvariable=arrend, width=50, state=DISABLED)
        e1.pack(side=LEFT, fill=X)

        self.f2 = Frame(self.lf)
        self.f2.pack(pady=5, fill=X)  #---------------------------

        self.inmuebleL = Label(self.f2, text='Inmueble:')
        self.inmuebleL.pack(side=LEFT)
        e2 = Entry(self.f2, textvariable=inmueble, state=DISABLED, width=48)
        e2.pack(side=LEFT, fill=X)

        self.f3 = Frame(self.lf)
        self.f3.pack(pady=5, fill=X)  #---------------------------

        self.inmuebleL = Label(self.f3, text='Código: ')
        self.inmuebleL.pack(side=LEFT)
        e3 = Entry(self.f3, textvariable=codigo, state=DISABLED, width=5)
        e3.pack(side=LEFT, fill=X)

        self.tel = Label(self.f3, text='Teléfono: ')
        self.tel.pack(side=LEFT)
        e4 = Entry(self.f3, textvariable=tel, state=DISABLED, width=15)
        e4.pack(side=LEFT, fill=X)

        self.precio = Label(self.f3, text='Arriendo $: ')
        self.precio.pack(side=LEFT)
        e5 = Entry(self.f3, textvariable=valor, state=DISABLED, width=15)
        e5.pack(side=LEFT, fill=X)

        #======================= DATOS PROPIETARIO =======================

        wrap = Frame(wrapper)
        wrap.pack(side=RIGHT)

        lf = LabelFrame(wrap, text="Propietario")
        lf.pack()  #-------------------------
        #lf.pack_forget()#-------------------------

        f0 = Frame(lf)
        f0.pack(pady=5, fill=X)  #---------------------------

        nombreL = Label(f0, text='Nombre: ')
        nombreL.pack(side=LEFT)
        e6 = Entry(f0, textvariable=prop, width=48, state=DISABLED)
        e6.pack(side=LEFT, fill=X)

        f1 = Frame(lf)
        f1.pack(pady=5, fill=X)  #---------------------------

        ccnitL = Label(f1, text='CC/Nit: ')
        ccnitL.pack(side=LEFT)
        e7 = Entry(f1, textvariable=nit, state=DISABLED, width=48)
        e7.pack(side=LEFT)

        f2 = Frame(wrap)
        f2.pack(pady=5, fill=X)  #---------------------------

        self.lb = Label(f2, text=None)
        self.lb.pack(side=LEFT)

        f3 = Frame(wrap)
        f3.pack(pady=5, fill=X)  #---------------------------
        """
		self.inmuebleL = Label(f2, text='Tipo Persona: ')
		self.inmuebleL.pack(side=LEFT)
		e8 = Entry(f2, textvariable=tp, state=DISABLED, width=40)
		e8.pack(side=LEFT,fill=X)
		"""

        l = Label(f3, text='SubTotal ')
        l.pack(side=LEFT)
        e8 = Entry(f3, textvariable=subtotal, state=DISABLED, width=12)
        e8.pack(side=LEFT, fill=X)

        l = Label(f3, text='IVA ')
        l.pack(side=LEFT)
        e9 = Entry(f3, textvariable=iva, state=DISABLED, width=12)
        e9.pack(side=LEFT, fill=X)

        l = Label(f3, text='Total ')
        l.pack(side=LEFT)
        e10 = Entry(f3, textvariable=total, state=DISABLED, width=12)
        e10.pack(side=LEFT, fill=X)

        f4 = Frame(wrap)
        f4.pack(pady=5, fill=X)  #---------------------------

        #========================= FACTURACIÓN =========================

        self.lf1 = LabelFrame(self, text="Periodo a facturar")
        self.lf1.pack(anchor=W, pady=5, fill=X)  #-------------------------

        self.f2 = Frame(self.lf1)
        self.f2.pack(pady=5, fill=X)  #---------------------------

        self.mesiniL = Label(self.f2, text='Mes inicial:')
        self.mesiniL.pack(padx=5, side=LEFT)

        CbxVlr = Combobox(self.f2,
                          textvariable=mes1,
                          values=meses,
                          width=10,
                          state=DISABLED)
        CbxVlr.set(mes)
        CbxVlr.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        self.yeariniL = Label(self.f2, text='Año:')
        self.yeariniL.pack(side=LEFT)
        self.yeariniE = Entry(self.f2,
                              textvariable=fechapago,
                              width=8,
                              state=DISABLED)
        fechapago.set(anio)
        self.yeariniE.pack(side=LEFT)

        self.mesfinL = Label(self.f2, text='Mes final:')
        self.mesfinL.pack(padx=5, side=LEFT)

        self.mesfinCbx = Combobox(self.f2,
                                  textvariable=mes2,
                                  values=meses,
                                  width=10)
        self.mesfinCbx.set(mes)
        self.mesfinCbx.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        self.yearfinL = Label(self.f2, text='Año:')
        self.yearfinL.pack(side=LEFT)
        self.yearfinE = Entry(self.f2, textvariable=fechapago, width=8)
        fechapago.set(anio)
        self.yearfinE.pack(side=LEFT)

        self.emptyL = Label(self.f2)  ###VACIO###
        self.emptyL.pack(padx=5, side=LEFT)

        pdfB = Button(self.f2,
                      text="Facturar",
                      command=agregar,
                      state=DISABLED)
        pdfB.pack(side=LEFT)

        #========================== TREEVIEW ===========================

        self.f3 = Frame(self)
        self.f3.pack(pady=5, fill=X)  #------------------------------------

        tree = Treeview(self.f3,
                        height=4,
                        show="headings",
                        columns=('col1', 'col2'))
        tree.pack(side=LEFT, fill=X, expand=1)

        tree.column('col1', width=250, anchor='center')
        tree.column('col2', width=5, anchor='center')

        tree.heading('col1', text='Descripción')
        tree.heading('col2', text='Valor')

        scroll = Scrollbar(self.f3, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)
        tree.bind("<Delete>", borrar)

        #======================== OBSERVACIONES ========================

        self.f4 = Frame(self)
        self.f4.pack(pady=5, fill=X)  #--------------------

        self.notesL = Label(self.f4, text='Observaciones:')
        self.notesL.pack(side=LEFT)

        self.f5 = Frame(self)
        self.f5.pack(pady=5, fill=X)  #-------------------

        observaciones = Text(self.f5, height=5)
        observaciones.pack(fill=X, side=LEFT, expand=1)

        #=========================== BOTONES ===========================

        footer = Frame(self)
        footer.pack()  #-------------------------------

        clean = Button(footer,
                       text='Cancelar',
                       bg='navy',
                       foreground='white',
                       activebackground='red3',
                       activeforeground='white',
                       command=cancelar)
        clean.pack(side=RIGHT)

        add = Button(footer,
                     text='Grabar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=grabar,
                     state=DISABLED)
        add.pack(side=RIGHT)
Ejemplo n.º 6
0
class Statistics(Toplevel):	
	def __init__(self,parent):
		Toplevel.__init__(self,parent)
		self.title("Статистика")	
		self.transient(parent)
		self.parent = parent

	#fields for parameters of search-----------------------------------------------------------------------------------
		paramframe = Frame(self,relief=GROOVE,width=200,bd=1)
		paramframe.pack(side=LEFT,fill=BOTH)

		Label(paramframe, text="Что вывести",width=20,height=2).grid(row=0,column=0,columnspan=2)
		what = Combobox(paramframe,state='readonly',values = [u"Расходы",u"Доходы",u"Всё"],height=5)
		what.set(u"Расходы")
		what.grid(row=1,column=0,columnspan=2)
		self.what = what		
		
		Label(paramframe, text="За период",height=2).grid(row=2,column=0,columnspan=2)
		when = Combobox(paramframe,state='readonly',values=[u"Сегодня",u"3 дня",u"5 дней",u"Неделю",u"3 недели",u"Месяц",u"Всё время"],height=5)
		when.set(u"Сегодня")
		when.grid(row=3,column=0,columnspan=2)
		self.when = when
		
		Label(paramframe,text="Упорядочить по",height=2).grid(row=4,column=0,columnspan=2)
		orderby = Combobox(paramframe,state='readonly',values=[u"Дата",u"Cумма",u"Категория"],height=3)
		orderby.set(u"Дата")
		orderby.grid(row=5,column=0,columnspan=2)
		
		self.orderby = orderby		

		Button(paramframe,text="Вывести",command=(lambda: self.getStatistics())).grid(row=6,column=0,columnspan=2)		

		Label(paramframe,text="Итого: ",height=20).grid(row=7,column=0)
		self.summarylbl = Label(paramframe,text='0.0',height=20)
		self.summarylbl.grid(row=7,column=1)


	#end ------------------------------------------------------------------------------------------------------------------
		
	#table -------------------------------------------------------------------------------------------------------------
		
		self.viewframe = Frame(self,relief=GROOVE,width=200,bd=1)
		self.viewframe.pack(side=RIGHT,fill=BOTH,expand=YES)

	#end ------------------------------------------------------------------------------------------------------------------

		self.geometry("%dx%d+%d+%d" % (1000,500,225,125))
		self.wait_window(self)
	
	def getStatistics(self):
		when = self.when.current()
		dateRange = ''
		
		if when == 0:
		#today
			dateRange = datetime.date.today()
		elif when == 1:
		#3 days
			dateRange = datetime.date.today() - datetime.timedelta(days=3)
		elif when == 2:
		#5 days
			dateRange = datetime.date.today() - datetime.timedelta(days=5)
		elif when == 3:
		#1 week
			dateRange = datetime.date.today() - datetime.timedelta(weeks=1)
		elif when == 4:
		#3 weeks
			dateRange = datetime.date.today() - datetime.timedelta(weeks=3)
		elif when == 5:
		#1 month
			dateRange = datetime.date.today() - datetime.timedelta(weeks=4)
		elif when == 6:
		#all 
			dateRange = '2012-01-01'
		
		orderby = self.orderby.current()
		if orderby == 0:
		#date
			orderby = 4
		elif orderby == 1:
		#summ
			orderby = 2
		elif orderby == 2:
		#c.title
			orderby = 6
			
		global payments
		payments.getPayments(1,str(dateRange))
		
		if hasattr(self, 'tree'):
			self.tree.destroy()
			
		self.tree = Treeview(self.viewframe,selectmode="extended",columns=('summ', 'comment', 'date','mul','category_title'))
		self.tree.heading('#0',text='№')
		self.tree.column('#0',width=15,anchor='center')
		
		
		self.tree.column('summ', width=60, anchor='center')
		self.tree.column('comment', anchor='center')
		self.tree.column('date', width=60, anchor='center')
		self.tree.column('mul', width=7, anchor='center')
		self.tree.column('category_title',  anchor='center')
		
		self.tree.heading('summ', text='Сумма')
		self.tree.heading('comment', text='Комметарий')
		self.tree.heading('date', text='Дата')
		self.tree.heading('mul', text='Количество')
		self.tree.heading('category_title', text='Категория')
		
		i=1
		summary = 0.0
		for row in payments.paymetsList:
			self.tree.insert('', i,str(i), text=str(i))
			self.tree.set(str(i),'summ',row['summ'])
			self.tree.set(str(i),'comment',row['comment'])
			self.tree.set(str(i),'date',row['date'])
			self.tree.set(str(i),'mul',row['mul'])
			self.tree.set(str(i),'category_title',row['category_title'])
			i+=1
			summary+=row['summ']*row['mul']
		
		self.summarylbl.config(text=str(summary))
		self.tree.pack(side=TOP, fill=BOTH, expand=YES)
		
		s = Scrollbar(self.tree, orient=VERTICAL, command=self.tree.yview)
		self.tree.configure(yscrollcommand=s.set)
		s.pack(side=RIGHT,fill=Y)
Ejemplo n.º 7
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global docID, nombre, refbanco, tree, busqueda, info, delete
		global e3
		
		lupa = PhotoImage(file='img/lupa.png')
		
		docID = StringVar()
		nombre = StringVar()
		refbanco = StringVar()
		busqueda = StringVar()
		info = IntVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		l0 = Label(self, text="BENEFICIARIOS", font="bold")
		l0.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		wrapper = Frame (self)
		wrapper.pack(side=TOP, fill=Y)
		#wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ
		
		f1 = Frame(wrapper)
		f1.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (f1, text="CC/Nit: ")
		l1.pack(side=LEFT)
		e1 = Entry (f1, textvariable=docID, width=20)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		e1.focus_set()
		
		f2 = Frame(wrapper)
		f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (f2, text="Nombre: ")
		l2.pack(side=LEFT)
		e2 = Entry (f2, textvariable=nombre, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		e2.bind("<KeyRelease>", caps)
		
		f3 = Frame(wrapper)
		f3.pack(pady=5, fill=X)#-----------------------------------
		
		l3 = Label (f3, text="Referencia Bancaria: ")
		l3.pack(side=LEFT)
		e3 = Entry (f3, textvariable=refbanco, width=60)
		e3.pack(side=LEFT, fill=X, expand=1)
		e3.bind("<KeyRelease>", caps)
		
		f4 = Frame(wrapper)
		f4.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (f4, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (f4, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		#========================== TREEVIEW ===========================
		
		f5 = Frame(wrapper)
		f5.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(f5, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=0, anchor='center')
		tree.column('col2', width=150, anchor='w')
		
		tree.heading('col1', text='CC/Nit')
		tree.heading('col2', text='Nombre Completo')
		
		scroll = Scrollbar(f5,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=scroll.set)
		
		f6 = Frame(wrapper)
		f6.pack(pady=5, fill=X)#-----------------------------------
		
		delete = Button (f6, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		delete.pack(side=RIGHT)
		
		e4 = Entry(f6, textvariable=busqueda)
		e4.pack(side=LEFT)
		e4.bind("<KeyRelease>", caps)
		
		b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar)
		b4.image = lupa
		b4.pack(side=LEFT)
		
		R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1)
		R1.pack(side=LEFT)
		R2 = Radiobutton (f6, text="Nombre", variable=info, value=2)
		R2.pack(side=LEFT)
		info.set(1)
Ejemplo n.º 8
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global docID, nombre, refbanco, tree, busqueda, info, delete
        global e3

        lupa = PhotoImage(file='img/lupa.png')

        docID = StringVar()
        nombre = StringVar()
        refbanco = StringVar()
        busqueda = StringVar()
        info = IntVar()

        #WIDGETS

        #=========================== HEADER ============================

        l0 = Label(self, text="BENEFICIARIOS", font="bold")
        l0.pack(pady=20, side=TOP)

        #=========================== WRAPPER ===========================

        wrapper = Frame(self)
        wrapper.pack(side=TOP, fill=Y)
        #wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ

        f1 = Frame(wrapper)
        f1.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(f1, text="CC/Nit: ")
        l1.pack(side=LEFT)
        e1 = Entry(f1, textvariable=docID, width=20)
        e1.pack(side=LEFT)
        e1.bind("<KeyRelease>", caps)
        e1.focus_set()

        f2 = Frame(wrapper)
        f2.pack(pady=5, fill=X)  #-----------------------------------

        l2 = Label(f2, text="Nombre: ")
        l2.pack(side=LEFT)
        e2 = Entry(f2, textvariable=nombre, width=60)
        e2.pack(side=LEFT, fill=X, expand=1)
        e2.bind("<KeyRelease>", caps)

        f3 = Frame(wrapper)
        f3.pack(pady=5, fill=X)  #-----------------------------------

        l3 = Label(f3, text="Referencia Bancaria: ")
        l3.pack(side=LEFT)
        e3 = Entry(f3, textvariable=refbanco, width=60)
        e3.pack(side=LEFT, fill=X, expand=1)
        e3.bind("<KeyRelease>", caps)

        f4 = Frame(wrapper)
        f4.pack(pady=5, fill=X)  #-----------------------------------

        b1 = Button(f4,
                    text="Cargar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=cargar)
        b1.pack(side=RIGHT)

        b2 = Button(f4,
                    text="Agregar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=agregar)
        b2.pack(side=RIGHT)

        #========================== TREEVIEW ===========================

        f5 = Frame(wrapper)
        f5.pack(pady=5, fill=X)  #-----------------------------------

        tree = Treeview(f5, show="headings", columns=('col1', 'col2'))
        tree.pack(side=LEFT, fill=X, expand=1)
        tree.column('col1', width=0, anchor='center')
        tree.column('col2', width=150, anchor='w')

        tree.heading('col1', text='CC/Nit')
        tree.heading('col2', text='Nombre Completo')

        scroll = Scrollbar(f5, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=scroll.set)

        f6 = Frame(wrapper)
        f6.pack(pady=5, fill=X)  #-----------------------------------

        delete = Button(f6,
                        text="Eliminar",
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=borrar)
        delete.pack(side=RIGHT)

        e4 = Entry(f6, textvariable=busqueda)
        e4.pack(side=LEFT)
        e4.bind("<KeyRelease>", caps)

        b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar)
        b4.image = lupa
        b4.pack(side=LEFT)

        R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1)
        R1.pack(side=LEFT)
        R2 = Radiobutton(f6, text="Nombre", variable=info, value=2)
        R2.pack(side=LEFT)
        info.set(1)
Ejemplo n.º 9
0
class Example(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.style = Style()
        self.style.theme_use("default")
        self.master.title("Log viewer")
        self.pack(fill=BOTH, expand=True)

        self.used = []  # List of currently plotted series ([str])
        self.series = {}  # List of all series ({str -> [number]})
        self.names = []  # List of all nodes in tree view ([str])
        self.queues = [] # List of all queues ([str])
        self.logs = {} # List of all text logs ({str -> [str]})

        self.rowconfigure(1, weight=1)
        self.columnconfigure(6, weight=3)
        self.columnconfigure(11, weight=1)

        # Series selection takes row 1-2, col 0-2
        self.series_ui = Treeview(self)
        self.series_ui.grid(row=1, column=0, columnspan=2, rowspan=2, sticky=N+S)
        self.series_ui.configure(show="tree")
        self.series_ui.bind("<Double-Button-1>", self.onselect)
        self.series_ui.tag_configure("graphall", foreground="#070")
        self.series_ui.tag_configure("graphnone", foreground="#000")
        self.series_ui.tag_configure("graphsome", foreground="#007")
        series_ui_scroll = Scrollbar(self, command=self.series_ui.yview, orient=VERTICAL)
        series_ui_scroll.grid(row=1, column=2, rowspan=2, sticky=N+S)
        self.series_ui["yscrollcommand"] = series_ui_scroll.set

        # The plot takes row 1-2, col 3-6
        move_mode = StringVar()
        move_mode.set("pan")
        show_path = IntVar()
        show_path.set(0)
        event_bars = IntVar()
        event_bars.set(1)
        show_debug = IntVar()
        show_debug.set(1)
        show_error = IntVar()
        show_error.set(1)
        show_warning = IntVar()
        show_warning.set(1)
        show_info = IntVar()
        show_info.set(1)
        self.plot = HackPlot(self, move_mode, show_path, event_bars,
                [(show_debug, "[DEBUG]"), (show_error, "[ERROR]"), (show_warning, "[WARNING]"), (show_info, "[INFO]")])
        self.plot.canvas.grid(row=1, column=3, columnspan=4, rowspan=2, sticky=N+S+E+W)
        # Text logs take row 1-2, col 7-12
        self.plot.listbox.grid(row=1, column=7, columnspan=5, sticky=N+S+E+W)
        listbox_yscroll = Scrollbar(self, command=self.plot.listbox.yview, orient=VERTICAL)
        listbox_yscroll.grid(row=1, column=12, sticky=N+S)
        self.plot.listbox["yscrollcommand"] = listbox_yscroll.set
        listbox_xscroll = Scrollbar(self, command=self.plot.listbox.xview, orient=HORIZONTAL)
        listbox_xscroll.grid(row=2, column=7, columnspan=5, sticky=E+W)
        self.plot.listbox["xscrollcommand"] = listbox_xscroll.set


        # Controls take row 0, col 0-12
        Button(self, text="Load Directory", command=self.loaddir).grid(row=0, column=0)
        Button(self, text="Load File", command=self.loadfile).grid(row=0, column=1)
        Button(self, text="Fit X", command=self.plot.fit_x).grid(row=0, column=3, sticky=W)
        Button(self, text="Fit Y", command=self.plot.fit_y).grid(row=0, column=4, sticky=W)
        Button(self, text="Fit Auto", command=self.plot.fit_auto).grid(row=0, column=5, sticky=W)
        Button(self, text="Fit Tele", command=self.plot.fit_tele).grid(row=0, column=6, sticky=W)
        # Plot controls in a subframe to manage padding so it doesn't look awful
        move_mode_control = Frame(self, padx=10)
        Radiobutton(move_mode_control, text="Pan", value="pan", variable=move_mode).grid(row=0, column=0, sticky=W)
        Radiobutton(move_mode_control, text="Zoom In", value="zoomin", variable=move_mode).grid(row=0, column=1, sticky=W)
        Radiobutton(move_mode_control, text="Zoom Out", value="zoomout", variable=move_mode).grid(row=0, column=2, sticky=W)
        move_mode_control.grid(row=0, column=7, sticky=W)
        Checkbutton(self, text="Event Bars", variable=event_bars, command=self.plot.show_textlogs).grid(row=0, column=8, sticky=W)
        Checkbutton(self, text="Debug", variable=show_debug, command=self.plot.show_textlogs).grid(row=0, column=9, sticky=W)
        Checkbutton(self, text="Error", variable=show_error, command=self.plot.show_textlogs).grid(row=0, column=10, sticky=W)
        Checkbutton(self, text="Warning", variable=show_warning, command=self.plot.show_textlogs).grid(row=0, column=11, sticky=W)
        Checkbutton(self, text="Info", variable=show_info, command=self.plot.show_textlogs).grid(row=0, column=12, sticky=W)
        Checkbutton(self, text="Directories", variable=show_path, command=self.plot.show_textlogs).grid(row=0, column=13, sticky=E)

    # Open Directory button clicked
    def loaddir(self):
        dirname = tkFileDialog.askdirectory(initialdir=log_dir)
        if dirname != "" and dirname != (): # Cancel and (x) not pressed
            # Empty the data
            self.used = []
            self.series = {}
            self.names = []
            self.queues = []
            self.logs = {}
            self.plot.reset()
            for node in self.series_ui.get_children():
                self.series_ui.delete(node)
            # For every csv file in the directory, checking recursively and alphabetically
            for subdirname, subsubdirnames, filenames in os.walk(dirname):
                subsubdirnames.sort()
                filenames.sort()
                for filename in filenames:
                    if filename.endswith(".csv") or filename.endswith(".log"):
                        # The name of the directory without the name of the directory selected,
                        # and the name of the file without the extension, separated by "."s
                        # For example if directory selected is /tmp/logs, subdirname is /tmp/logs/beta/666,
                        # and filename is foo.csv, nodeprefix is "beta.666.foo".
                        nodeprefix = ".".join(subdirname[len(dirname)+1:].split("/") + [filename[:-4]])
                        if nodeprefix.startswith("."):
                            nodeprefix = nodeprefix[1:]
                        # Add the file's data
                        self.readfile(subdirname + "/" + filename, nodeprefix)
            for name in self.names:
                # Add name to (name with everything after last dot removed), as the last child,
                # with text (everything after last dot of name) and tags graphnone and (whether name represents data)
                self.series_ui.insert(".".join(name.split(".")[0:-1]), "end", name,
                        text=name.split(".")[-1], tags=["graphnone"])

    # Open File button clicked
    def loadfile(self):
        filename = tkFileDialog.askopenfilename(filetypes=[("CSV Files", "*.csv"), ("Text log file", "*.log")], initialdir=log_dir)
        if filename != "" and filename != (): # Cancel and (x) not pressed
            # Empty the data
            self.used = []
            self.series = {}
            self.names = []
            self.queues = []
            self.logs = {}
            self.plot.reset()
            for node in self.series_ui.get_children():
                self.series_ui.delete(node)
            # Add the file's data
            self.readfile(filename, "")
            for name in self.names:
                # Add name to (name with everything after last dot removed), as the last child,
                # with text (everything after last dot of name) and tags graphnone and (whether name represents data)
                self.series_ui.insert(".".join(name.split(".")[0:-1]), "end", name,
                        text=name.split(".")[-1], tags=["graphnone"])

    # Add a file's data
    # nodeprefix is a string to add before every name in the file, represents file's name in the tree
    def readfile(self, filename, nodeprefix):
        try:
            if filename.endswith(".csv"):
                # For csv files this will always be concatenated with something
                if nodeprefix != "":
                    nodeprefix += "."
                csvfile = open(filename, "rb")
                reader = csv.DictReader(csvfile)
                series = {}
                self.queues.append(nodeprefix[:-1])
                for name in reader.fieldnames:
                    # Add ancestor_names to names, without creating duplicates
                    self.names = list(OrderedDict.fromkeys(self.names + ancestor_names(nodeprefix + name)))
                    # Create a series for this field
                    series[nodeprefix + name] = []
                for row in reader:
                    for name in reader.fieldnames:
                        try:
                            # Add cell to series if it represents a number
                            series[nodeprefix + name].append(float(row[name]))
                        except ValueError:
                            # Not a number, no problem, could be game_specific_string or something
                            pass
                self.series.update(series)
            else:
                self.names.append(nodeprefix)
                self.logs[nodeprefix] = open(filename, "r").readlines()
        except IOError:
            tkMessageBox.showerror(message="Could not open file: " + str(filename))

    # Tree element was double clicked
    def onselect(self, _):
        series = self.series_ui.focus()
        # Set it to graph if no children are graphed, and not to graph if all or some are
        self.setgraphed(series, self.series_ui.tag_has("graphnone", series))
        self.checkgraphed(series)

    # Set a node and its children to be either all or none graphed
    def setgraphed(self, node, shouldgraph):
        if shouldgraph:
            self.series_ui.item(node, tags=["graphall"])
            # If the node represents data and it isn't already graphed, graph it
            if node in self.series and node not in self.used:
                self.used.append(node)
                # Timestamp is queue that contains node + ".timestamp"
                timestamp_name = [queue for queue in self.queues if node.startswith(queue)][0] + ".timestamp"
                self.plot.add_plot(self.series[timestamp_name], self.series[node], node)
            if node in self.logs and node not in self.used:
                self.used.append(node)
                self.plot.add_textlog(self.logs[node], node)
            # If nothing else is plotted, fit the plot to this
            if len(self.used) == 1:
                self.plot.fit_x()
                self.plot.fit_y()
            for child in self.series_ui.get_children(node):
                self.setgraphed(child, True)
        else:
            # Set tags to be (whether node represents data) and graphnone
            self.series_ui.item(node, tags=["graphnone"])
            if node in self.used:
                self.used.remove(node)
                if node in self.logs:
                    self.plot.remove_textlog(node)
                if node in self.series:
                    self.plot.remove_plot(node)
            for child in self.series_ui.get_children(node):
                self.setgraphed(child, False)

    # Update the tags (and color) on a node and its ancestors, should always be called after setgraphed
    def checkgraphed(self, node):
        # Top level nodes are children of ""
        if node == "":
            return
        # True unless a child doesn't share this tag or there are no children
        graphall = True
        graphnone = True
        for child in self.series_ui.get_children(node):
            if not self.series_ui.tag_has("graphall", child):
                graphall = False
            if not self.series_ui.tag_has("graphnone", child):
                graphnone = False
        graphtag = ""
        if graphall and graphnone:
            # There are no children, check the used list instead
            graphtag = "graphall" if node in self.used else "graphnone"
        elif graphall:
            graphtag = "graphall"
        elif graphnone:
            graphtag = "graphnone"
        else:
            graphtag = "graphsome"
        # Set tags to be (whether node represents data) and the computed status
        self.series_ui.item(node, tags=[graphtag])
        # Now that the status of this node is known, check the parent
        self.checkgraphed(self.series_ui.parent(node))
Ejemplo n.º 10
0
        def __init__(self, parent, controller):
			Frame.__init__(self, parent)
			
			#INSTANCIAS
			global cc, nombre, pago, ref, cod, desc, valor, resultado, total, tiempo, mes, anio, fechapago
			#INSTANCIAS DE LOS WIDGETS
			global e1, e2, e3, e4, e5, tree, l8, lb
			
			cc = IntVar()
			nombre = StringVar()
			pago = StringVar()
			ref = StringVar()
			cod = StringVar()
			desc = StringVar()
			valor = DoubleVar()
			
			tiempo = datetime.date.today()
			anio = time.strftime("%Y")
			mes = time.strftime("%B")
			fechapago = StringVar()
			
			total = 0.0
			resultado = DoubleVar()
			
			tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"]
			
			lupa = PhotoImage(file='img/lupa.png')
			
			tbanktype = ['Corriente','Ahorro']
			fpago = ['Efectivo','Transferencia']
			
			#BUSQUEDA = ["Nombre","CC/Nit"]
			busqueda = StringVar()
			busqueda.trace("w", lambda name, index, mode: buscar())
			dato = StringVar()
			
			#WIDGETS
			
			#========================= HEADER ==============================
			
			self.titleL = Label(self, text="GASTOS", font="bold")
			self.titleL.pack(pady=20, side=TOP)
			
			#========================== WRAPPER ============================
			
			self.wrapper = Frame (self)
			self.wrapper.pack(side=LEFT, fill=Y)
			#Esto centro el wrapper
			#self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)
			
			#======================== BENEFICIARIO =======================
			
			self.lf1 = LabelFrame(self.wrapper, text="Beneficiario")
			self.lf1.pack(fill=X, ipady=5)
			
			self.f0 = Frame(self.lf1)
			self.f0.pack(pady=5, fill=X)#-----------------------------------
			
			l1 = Label(self.f0, text='CC/Nit:')
			l1.pack(side=LEFT)
			
			e1 = Entry(self.f0, textvariable=cc)
			e1.pack(side=LEFT)
			e1.bind('<Return>', buscarB)
			
			b0 = Button(self.f0, text='Buscar:', image=lupa, command=topBeneficiarios)
			b0.pack(side=LEFT)
			
			l2 = Label(self.f0, text='Nombre:')
			l2.pack(side=LEFT)
			e2 = Entry(self.f0, textvariable=nombre)
			e2.pack(side=LEFT, fill=X, expand=1)
			
			self.f1 = Frame(self.lf1)
			self.f1.pack(pady=5, fill=X)#-----------------------------------
			
			l3 = Label(self.f1, text='Forma de Pago:')
			l3.pack(side=LEFT)
			Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15)
			Cbx.set('Efectivo')
			Cbx.pack(side=LEFT)
			
			l4 = Label(self.f1, text='Ref. Bancaria:')
			l4.pack(side=LEFT)
			e3 = Entry(self.f1, textvariable=ref)
			e3.pack(side=LEFT, fill=X, expand=1)
			
			b1 = Button(self.f1, text='Buscar:', image=lupa)
			b1.image=lupa
			b1.pack(side=LEFT)
			
			#======================== CONCEPTO ========================
			
			self.lf2 = LabelFrame(self.wrapper, text="Concepto")
			self.lf2.pack(fill=X, ipady=5)
			
			self.f2 = Frame(self.lf2)
			self.f2.pack(pady=5, fill=X)#-------------------------------
			
			l5 = Label(self.f2, text='Código:')
			l5.pack(side=LEFT)
			e4 = Entry(self.f2, textvariable=cod)
			e4.pack(side=LEFT)
			e4.bind('<Return>', buscarC)
			
			b2 = Button(self.f2, text='Buscar:', image=lupa, command=topCtasContables)
			b2.pack(side=LEFT)
			
			self.f3 = Frame(self.lf2)
			self.f3.pack(pady=5, fill=X)#-------------------------------
			
			l6 = Label(self.f3, text='Descripción:')
			l6.pack(side=LEFT)
			e5 = Entry(self.f3, textvariable=desc, state=DISABLED)
			e5.pack(side=LEFT, fill=X, expand=1)
			
			l7 = Label(self.f3, text='Valor:')
			l7.pack(side=LEFT)
			e6 = Entry(self.f3, width=15, textvariable=valor)
			e6.pack(side=LEFT)
			
			b3 = Button(self.f3, text='Agregar:', command=agregar)
			b3.pack(side=LEFT)
			
			#-------------------------- TREEVIEW ---------------------------
			
			self.f4 = Frame(self.wrapper)
			self.f4.pack(pady=5,fill=X)
			
			tree = Treeview(self.f4, height=4, show="headings", columns=('col1','col2','col3'))
			tree.pack(side=LEFT, fill=X, expand=1)
			tree.column('col1', width=20, anchor='center')
			tree.column('col2', width=200, anchor='center')
			tree.column('col3', width=10, anchor='center')
			
			tree.heading('col1', text='Código')
			tree.heading('col2', text='Concepto')
			tree.heading('col3', text='Valor')
			
			scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
			tree.configure(yscrollcommand=scroll.set)
			tree.bind("<Delete>", borrar)
			
			#-------------------------- RESULTADOS ---------------------------
			
			self.f5 = Frame(self.wrapper)
			self.f5.pack(pady=5,fill=X)#-------------------
			
			l8 = Label(self.f5, textvariable=resultado, fg="red", bg="white", anchor='e', font="bold, 22", relief= SUNKEN)
			l8.pack(fill=X, side=RIGHT, expand=1)
			
			#-------------------------- FOOTER ---------------------------
			
			self.fBtn = Frame(self.wrapper)
			self.fBtn.pack()#-------------------------------
			
			clean = Button(self.fBtn, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
			clean.pack(side=RIGHT)
			
			add = Button(self.fBtn, text='Grabar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=grabar)
			add.pack(side=RIGHT)
			
			#========================= ASIDE ===========================
			
			self.aside = Frame(self)
			self.aside.pack(side=TOP, fill=BOTH)
			
			self.wrap1 = Frame(self.aside)
			self.wrap1.pack()
			
			self.viewer = Label(self.wrap1, text="LISTA DE GASTOS")
			self.viewer.pack()
			
			scroll = Scrollbar(self.wrap1, orient=VERTICAL)
			scroll.pack(side=RIGHT, fill=Y)
			
			lb = Listbox(self.wrap1, yscrollcommand=scroll.set, height=20, width=30)
			scroll.config (command=lb.yview)
			lb.pack(fill=BOTH)
			
			self.wrap2 = Frame(self.aside)
			self.wrap2.pack()
			
			load = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista)
			load.pack(fill=X)
			
			delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=None)
			delete.pack(fill=X)
			
			edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=None)
			edit.pack(fill=X)
			
			buscador = Label(self.wrap2, text="Buscar por Número:")
			buscador.pack()
			E = Entry(self.wrap2, textvariable=busqueda, width=24)
			E.pack()
			E.bind("<KeyRelease>", caps)
Ejemplo n.º 11
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global cbox, inmueble, loc, nit, nombre, carpeta, grupo, porcentaje, tree, busqueda
        global e1, e2, nitE

        lupa = PhotoImage(file='img/lupa.png')

        inmueble = IntVar()
        loc = StringVar()
        nit = StringVar()
        nombre = StringVar()
        carpeta = IntVar()
        grupo = IntVar()
        porcentaje = DoubleVar()

        lupa = PhotoImage(file='img/lupa.png')

        #BUSQUEDA = ["Nombre","CC/Nit"]
        busqueda = StringVar()
        #busqueda.trace("w", lambda name, index, mode: buscar())
        dato = StringVar()

        #WIDGETS

        #=========================== HEADER ============================

        self.titleL = Label(self,
                            text="RELACIÓN INMUEBLES/PROPIETARIO",
                            font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #=========================== WRAPPER ===========================

        self.wrapper = Frame(self)
        self.wrapper.pack(side=TOP, fill=Y)

        self.f = Frame(self.wrapper)
        self.f.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(self.f, text='Inmueble:')
        l1.pack(side=LEFT)

        e1 = Entry(self.f, textvariable=inmueble)
        e1.pack(side=LEFT)
        e1.bind('<Return>', buscarI)

        b1 = Button(self.f, text="Buscar", image=lupa, command=topInmueble)
        b1.image = lupa
        b1.pack(side=LEFT)

        self.f0 = Frame(self.wrapper)
        self.f0.pack(pady=5, fill=X)  #-----------------------------------

        l2 = Label(self.f0, text="Dirección: ")
        l2.pack(side=LEFT)

        e2 = Entry(self.f0, textvariable=loc, width=90, state=DISABLED)
        e2.pack(side=LEFT, fill=X, expand=1)

        self.f1 = Frame(self.wrapper)
        self.f1.pack(pady=5, fill=X)  #-----------------------------------

        self.nit = Label(self.f1, text="CC/Nit")
        self.nit.pack(side=LEFT)

        nitE = Entry(self.f1, textvariable=nit)
        nitE.pack(side=LEFT)
        nitE.bind('<Return>', buscarP)

        self.add = Button(self.f1,
                          text="Buscar",
                          image=lupa,
                          command=topPropietario)
        self.add.pack(side=LEFT)

        self.f2 = Frame(self.wrapper)
        self.f2.pack(pady=5, fill=X)  #-----------------------------------

        self.nombre = Label(self.f2, text="Nombre: ")
        self.nombre.pack(side=LEFT)
        self.nombreE = Entry(self.f2,
                             textvariable=nombre,
                             width=90,
                             state=DISABLED)
        self.nombreE.pack(side=LEFT, fill=X, expand=1)

        self.f3 = Frame(self.wrapper)
        self.f3.pack(pady=5, fill=X)  #-----------------------------------

        self.carpeta = Label(self.f3, text="Carpeta: ")
        self.carpeta.pack(side=LEFT)
        self.carpetaE = Entry(self.f3, textvariable=carpeta, width=5)
        self.carpetaE.pack(side=LEFT)
        carpeta.set(1)

        self.grupo = Label(self.f3, text="Grupo: ")
        self.grupo.pack(side=LEFT)
        self.grupoE = Entry(self.f3, textvariable=grupo, width=5)
        self.grupoE.pack(side=LEFT)
        grupo.set(1)

        self.porcentaje = Label(self.f3, text="Porcentaje: ")
        self.porcentaje.pack(side=LEFT)
        self.porcentajE = Entry(self.f3, textvariable=porcentaje, width=5)
        self.porcentajE.pack(side=LEFT)

        self.chkb0 = Checkbutton(self.f3, text="Representante")
        self.chkb0.pack(side=LEFT)

        self.update = Button(self.f3,
                             text="Cargar",
                             bg='navy',
                             foreground='white',
                             activebackground='red3',
                             activeforeground='white',
                             command=cargar)
        self.update.pack(side=RIGHT)

        self.add = Button(self.f3,
                          text="Agregar",
                          bg='navy',
                          foreground='white',
                          activebackground='red3',
                          activeforeground='white',
                          command=agregar)
        self.add.pack(side=RIGHT)

        self.f4 = Frame(self.wrapper)
        self.f4.pack(pady=5, fill=X)  #-----------------------------------

        tree = Treeview(self.f4,
                        show="headings",
                        columns=('col1', 'col2', 'col3', 'col4', 'col5',
                                 'col6'))
        tree.pack(side=LEFT, fill=X, expand=1)

        tree.column('col1', width=5, anchor='center')
        tree.column('col2', width=150, anchor='center')
        tree.column('col3', width=5, anchor='center')
        tree.column('col4', width=150, anchor='center')
        tree.column('col5', width=1, anchor='center')
        tree.column('col6', width=1, anchor='center')

        tree.heading('col1', text='Cod')
        tree.heading('col2', text='Imnueble')
        tree.heading('col3', text='CC/nit')
        tree.heading('col4', text='Dueño')
        tree.heading('col5', text='Grupo')
        tree.heading('col6', text='%')

        self.scroll = Scrollbar(self.f4, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=self.scroll.set)
        """
        #EJEMPLO 2 SÍ FUNCIONA (0)
                self.tree = Treeview(self.f4, height=5, columns=2)
                self.tree.pack()
                self.tree.heading('#0', text='CC/Nit', anchor=W)
                self.tree.heading(2, text='Nombre', anchor=W)"""

        self.f5 = Frame(self.wrapper)
        self.f5.pack(pady=5, fill=X)  #-----------------------------------

        self.delete = Button(self.f5,
                             text="Eliminar",
                             bg='navy',
                             foreground='white',
                             activebackground='red3',
                             activeforeground='white',
                             command=borrar)
        self.delete.pack(side=RIGHT)

        e3 = Entry(self.f5, textvariable=busqueda)
        e3.pack(side=LEFT)
        #e3.bind("<KeyRelease>", caps)

        b3 = Button(self.f5, text='BUSCAR', image=lupa, command=buscar)
        b3.image = lupa
        b3.pack(side=LEFT)
class wine_DB_manager:  #Class for wrapping TKinter widgets
    def __init__(self, master):  #Initilize the attributes of the class

        master.minsize(width=600, height=700)  #Set window size and title
        master.title("Member and Store Manager")

        master.grid_columnconfigure(
            0, weight=1
        )  #Configure first and last columns for centering columns 1-5
        master.grid_columnconfigure(6, weight=1)
        master.grid_rowconfigure(
            12, weight=1
        )  #Configure last row for filling left over space at the bottom

        self.imp_store_label = Label(
            master, text="Import Store Information (.CSV)"
        )  #Initilize lable, entry, and buttons for importing stores
        self.imp_store_entry = Entry(master, width=70)
        self.imp_store_browse_button = Button(
            master,
            text="Browse",
            command=lambda: self.browse_for_CSV("store"))
        self.imp_store_import_button = Button(
            master,
            text="Import",
            command=lambda: self.import_to_DB(self.imp_store_entry.get(),
                                              "store"))

        self.imp_member_label = Label(
            master, text="Import Member Information (.CSV)"
        )  #Initilize lable, entry, and buttons for importing members
        self.imp_member_entry = Entry(master, width=70)
        self.imp_member_browse_button = Button(
            master,
            text="Browse",
            command=lambda: self.browse_for_CSV("member"))
        self.imp_member_import_button = Button(
            master,
            text="Import",
            command=lambda: self.import_to_DB(self.imp_member_entry.get(),
                                              "member"))

        self.horz_divider = Frame(
            master, height=1, width=500, bg="black"
        )  #Initilize a frame shaped as a horizonal line as a divider

        self.view_all_members_button = Button(
            master,
            text="View All Members",
            width=17,
            command=lambda: self.select_all_members()
        )  #Initilize button for selecting all members and displaying them in tree

        self.zip_label = Label(
            master, text="Zip Code"
        )  #Initilize lable, entry, combobox, and buttons for
        self.zip_entry = Entry(
            master,
            width=10)  #finding who paid dues by zip code and month paid
        self.month_label = Label(master, text="Month")
        self.month_combobox = Combobox(master, width=10)
        self.month_combobox['values'] = ('January', 'February', 'March',
                                         'April', 'May', 'June', 'July',
                                         'August', 'September', 'October',
                                         'November', 'December')
        self.find_users_that_paid = Button(
            master,
            text="Current Paid Users",
            width=20,
            command=lambda: self.select_paid_dues_month(
                self.zip_entry.get(), self.month_combobox.current()))

        self.state_label = Label(
            master,
            text="State")  #Initilize lable, entry, combobox, and buttons for
        self.state_combobox = Combobox(
            master,
            width=3)  #finding users who have joined the club since a date
        self.state_combobox['values'] = ('MD', 'NC', 'PA', 'VA', 'WV'
                                         )  #and belong to a specific state
        self.date_label = Label(master, text="Date (YYYY-MM-DD)")
        self.date_entry = Entry(master, width=10)
        self.find_users_that_joined = Button(
            master,
            text="Users Joined Since",
            width=20,
            command=lambda: self.select_users_joined_since(
                self.state_combobox.get(), self.date_entry.get()))

        self.users_that_love_total_wine = Button(
            master,
            text="Users that Love Total Wine",
            width=20,
            command=lambda: self.select_users_love_Tot_Wine(
            ))  #Initilize button for finding users that love Total Wines

        self.users_favorite_stores = Button(
            master,
            text="User's Favorite Stores",
            width=20,
            command=lambda: self.select_users_fav_stores()
        )  #Initilize button for finding users, their favorite stores, and store locations

        self.table_tree = Treeview(
            master, selectmode="extended")  #Initilize tree for data viewing
        self.table_tree["columns"] = (
            "one", "two", "three", "four", "five", "six", "seven", "eight",
            "nine", "ten", "eleven")  #Provide max column count and identifiers
        for columns in self.table_tree[
                "columns"]:  #For loop to add all columns
            self.table_tree.column(columns, width=70, anchor=W)
        self.table_tree['show'] = 'headings'  #Remove empty identity column

        self.vert_scroll_bar = Scrollbar(
            orient="vertical",
            command=self.table_tree.yview)  #Initilize scroll bar
        self.table_tree.configure(yscrollcommand=self.vert_scroll_bar.set
                                  )  #Add scroll bar to table_tree

        self.imp_store_label.grid(
            sticky="W", row=1, column=1, padx=10,
            pady=(20, 0))  #Grid positioning for all initialized attributes
        self.imp_store_entry.grid(sticky="W",
                                  row=2,
                                  column=1,
                                  columnspan=3,
                                  padx=10)
        self.imp_store_browse_button.grid(row=2, column=4, padx=10)
        self.imp_store_import_button.grid(row=2, column=5)

        self.imp_member_label.grid(sticky="W", row=3, column=1, padx=10)
        self.imp_member_entry.grid(sticky="W",
                                   row=4,
                                   column=1,
                                   columnspan=3,
                                   padx=10)
        self.imp_member_browse_button.grid(row=4, column=4, padx=10)
        self.imp_member_import_button.grid(row=4, column=5)

        self.horz_divider.grid(row=5, column=0, columnspan=7, pady=20)

        self.view_all_members_button.grid(row=6, column=1, columnspan=5)

        self.zip_label.grid(sticky="W", row=7, column=1, pady=(15, 0))
        self.zip_entry.grid(sticky="W", row=8, column=1, pady=5)
        self.month_label.grid(sticky="W",
                              row=7,
                              column=1,
                              padx=(100, 0),
                              pady=(15, 0))
        self.month_combobox.grid(sticky="W",
                                 row=8,
                                 column=1,
                                 padx=(100, 0),
                                 pady=5)
        self.find_users_that_paid.grid(sticky="W",
                                       row=9,
                                       column=1,
                                       columnspan=3,
                                       pady=5)

        self.state_label.grid(sticky="W", row=7, column=4, pady=(15, 0))
        self.state_combobox.grid(sticky="W", row=8, column=4, pady=5)
        self.date_label.grid(sticky="W",
                             row=7,
                             column=4,
                             columnspan=3,
                             padx=(85, 0),
                             pady=(15, 0))
        self.date_entry.grid(sticky="W",
                             row=8,
                             column=4,
                             columnspan=2,
                             padx=(85, 0),
                             pady=5)
        self.find_users_that_joined.grid(sticky="W",
                                         row=9,
                                         column=4,
                                         columnspan=2,
                                         pady=5)

        self.users_that_love_total_wine.grid(sticky="W",
                                             row=10,
                                             column=1,
                                             columnspan=3,
                                             pady=(15, 0))

        self.users_favorite_stores.grid(sticky="W",
                                        row=10,
                                        column=4,
                                        columnspan=2,
                                        pady=(15, 0))

        self.table_tree.grid(sticky="NWES",
                             row=11,
                             column=0,
                             columnspan=7,
                             rowspan=2,
                             pady=10,
                             padx=(10, 0))
        self.vert_scroll_bar.grid(sticky="NWES",
                                  row=11,
                                  column=7,
                                  rowspan=2,
                                  pady=10,
                                  padx=(0, 10))

    def browse_for_CSV(
        self, CSV_type
    ):  #Class method for browse buttons. Used for passing file path to TKinter entries

        file = tkFileDialog.askopenfile(
            parent=root, mode='rb',
            title='Choose a file')  #Opens browse for file window

        if (file != None):  #If file exists read into data and close file

            data = file.read()
            file.close()

            if (
                    CSV_type == "store"
            ):  #In order to resuse code, this method works for both buttons
                self.imp_store_entry.delete(
                    0, END)  #through using a passed button identity variable
                self.imp_store_entry.insert(0, os.path.abspath(file.name))

            else:
                self.imp_member_entry.delete(0, END)  #Empties entry widget
                self.imp_member_entry.insert(
                    0, os.path.abspath(file.name)
                )  #Inserts file path into entry widget using os.path import
        else:  #Catches no file selected possibility
            tkMessageBox.showinfo("Error", "No File Selected")

        return None

    def create_DB_connection(
        self
    ):  #Class method for opening a database connection to the pythonsqlite.db file

        try:
            DB_file = "SQLite_db\pythonsqlite.db"
            conn = sqlite3.connect(DB_file)
            return conn

        except Error as e:  #Catches non-connectivity errors
            print(e)

        return None

    def import_to_DB(
        self, file_path, CSV_type
    ):  #Class method for import buttons. Used to open csv files from path string
        #in entry widgets. Then opens db connection to import data to db
        try:
            self.CSV_file = open(file_path, "r")  #Opens CSV file in read mode
        except IOError as e:  #Catches file not found error
            tkMessageBox.showinfo("Error", "File Not Found")
            return

        CSV_reader = csv.reader(
            self.CSV_file
        )  #Reads CSV file into CSV_reader using csv.reader import
        conn = self.create_DB_connection()  #Calls for DB connection to open

        cur = conn.cursor()

        if (
                CSV_type == "store"
        ):  #In order to resuse code, this method works for both buttons by passed type.
            if (next(CSV_reader)[0][0:8] !=
                    "Store id"):  #Checks CSV for proper store headings
                tkMessageBox.showinfo(
                    "CSV Type Error",
                    "Please Import a CSV file formated for store data.")
                self.CSV_file.close(
                )  #If not proper headings close file and display message
                return
            else:  #Create table Stores
                cur.execute(
                    '''CREATE TABLE IF NOT EXISTS Stores (                                                                                 
                                store_id INTEGER PRIMARY KEY, 
                                store_name VARCHAR, 
                                location VARCHAR)''')

                for row in CSV_reader:  #Insert new values for each row in CSV
                    cur.execute(
                        '''INSERT OR IGNORE INTO Stores (                                                                                  
                                    store_id, 
                                    store_name, 
                                    location) 
                                    VALUES (?, ?, ?)''', row)
                tkMessageBox.showinfo(
                    "Success!",
                    "Successfully Updated the Database")  #Display confirmation
                self.imp_store_entry.delete(0, END)  #Clear import entry

        else:
            if (next(CSV_reader)[0][0:6] !=
                    "Member"):  #Checks CSV for proper member headings
                tkMessageBox.showinfo(
                    "CSV Type Error",
                    "Please Import a CSV file formated for member data.")
                self.CSV_file.close(
                )  #If not proper headings close file and display message
                return
            else:  #Create table Members
                cur.execute('''CREATE TABLE IF NOT EXISTS Members (     
                                member_id INTEGER PRIMARY KEY, 
                                last_name VARCHAR, 
                                first_name VARCHAR, 
                                street VARCHAR, 
                                city VARCHAR, 
                                state VARCHAR, 
                                zip VARCHAR, 
                                phone VARCHAR, 
                                favorite_store INTEGER, 
                                date_joined DATE, 
                                dues_paid DATE, 
                                FOREIGN KEY(favorite_store) 
                                REFERENCES Stores(store_id))''')

                for row in CSV_reader:  #Insert new values for each row in CSV
                    cur.execute(
                        '''INSERT OR IGNORE INTO Members (
                                        member_id, 
                                        last_name, 
                                        first_name, 
                                        street, 
                                        city , 
                                        state, 
                                        zip, 
                                        phone, 
                                        favorite_store, 
                                        date_joined, 
                                        dues_paid) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                        row)
                tkMessageBox.showinfo("Success!",
                                      "Successfully Updated the Database")
                self.imp_member_entry.delete(0, END)

        self.CSV_file.close()  #Close CSV file
        conn.commit()  #Commit DB changes
        conn.close()  #Close DB Connection

        return None

    def generate_member_column_names(
            self
    ):  #Class utility method for adding member column headers to tree

        all_member_column_names = ("Member ID", "Last Name", "First Name",
                                   "Street", "City", "State", "Zip Code",
                                   "Phone", "Favorite Store", "Date Joined",
                                   "Dues Paid")

        for index, columns in enumerate(self.table_tree["columns"]
                                        ):  #For loop to add all column headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        return None

    def select_all_members(
        self
    ):  #Class method for View All Members Buttons and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        cur.execute("SELECT * FROM Members ORDER BY last_name ASC"
                    )  #SQL Statement to SELECT all members and their data.

        rows = cur.fetchall()  #Fetches data into rows

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_paid_dues_month(
        self, zip, month
    ):  #Class method for Current Paid User Button and outputs new data to tree

        month = month + 1  #Add 1 to month index count since it range is 0-11 and months are 1-12
        if (month < 10):
            self.month_string = "0" + str(month)

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open

        if (month not in range(1, 12)):  #If no month selected display message
            tkMessageBox.showinfo("Error", "No Month Selected")
            return

        if (len(zip) != 5):  #If zip not 5 digits display message
            tkMessageBox.showinfo("Error", "Enter a Zip Code")
            return

        try:
            cur.execute("SELECT * FROM Members WHERE zip = " + zip +
                        " AND strftime('%m',dues_paid) = '" +
                        self.month_string +
                        "'")  #If zip is numeric execute Select Statement
        except Error as e:  #Catches error if zip not numeric
            tkMessageBox.showinfo("Error", "Enter a Zip Code")
            return

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_joined_since(
        self, state, the_date
    ):  #Class method for Current Paid User Button and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open

        if state == "":  #if no state selected display message
            tkMessageBox.showinfo("Error", "No State Selected")
            return

        try:  #Checks date format YYYY-MM-DD
            datetime.datetime.strptime(the_date, '%Y-%m-%d')
        except ValueError:  #Catches invalid date format
            tkMessageBox.showinfo(
                "Error", "Incorrect data format, should be YYYY-MM-DD")
            return

        cur.execute(
            "SELECT * FROM Members WHERE state = '" + state +
            "' AND date_joined > '" + the_date + "'"
        )  #Execute Select members Where state and date are what user selected.

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        self.generate_member_column_names(
        )  #Call utility to generate column member headers

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_love_Tot_Wine(
        self
    ):  #Class method for Users That Love Tot Wine and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        #Execute Select Where, and Join on foreign key values.
        cur.execute('''SELECT Members.last_name,
                            Members.first_name, 
                            Stores.store_name 
                            FROM Members 
                            JOIN Stores 
                            ON Members.favorite_store = Stores.store_id 
                            WHERE favorite_store = '3' ''')

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        all_member_column_names = ("Last Name", "First Name", "Favorite Store",
                                   "", "", "", "", "", "", "", "")

        for index, columns in enumerate(
                self.table_tree["columns"]
        ):  #Generate *custom* column member headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None

    def select_users_fav_stores(
        self
    ):  #Class method for Users Favorite Stores and outputs new data to tree

        cur = self.create_DB_connection().cursor(
        )  #Calls for DB connection to open
        #Execute Select Where, and Join on foreign key values.
        cur.execute('''SELECT Members.last_name,
                    Members.first_name, 
                    Stores.store_name, 
                    Stores.location
                    FROM Members 
                    JOIN Stores 
                    ON Members.favorite_store = Stores.store_id ''')

        rows = cur.fetchall()

        self.table_tree.delete(*self.table_tree.get_children()
                               )  #Deletes old data in tree if present

        all_member_column_names = ("Last Name", "First Name", "Favorite Store",
                                   "Location", "", "", "", "", "", "", "")

        for index, columns in enumerate(
                self.table_tree["columns"]
        ):  #Generate *custom* column member headers
            self.table_tree.heading(columns,
                                    text=all_member_column_names[index])

        for index, row in enumerate(
                rows):  #Inserts sql data into tree rows for viewing
            self.table_tree.insert('', index, values=(row))

        self.create_DB_connection().close()  #Close DB Connection
        return None
Ejemplo n.º 13
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global codigo, ctacontable, nombre, desc, tree

        lupa = PhotoImage(file='img/lupa.png')

        codigo = StringVar()
        ctacontable = StringVar()
        nombre = StringVar()
        desc = StringVar()

        #WIDGETS

        #=========================== HEADER ============================

        self.titleL = Label(self, text="CONCEPTO DE GASTOS", font="bold")
        self.titleL.pack(pady=20, side=TOP)

        #=========================== WRAPPER ===========================

        self.wrapper = Frame(self)
        self.wrapper.pack(side=TOP, fill=Y)

        self.f0 = Frame(self.wrapper)
        self.f0.pack(pady=5, fill=X)  #-----------------------------------

        l1 = Label(self.f0, text="Código:")
        l1.pack(side=LEFT)
        e1 = Entry(self.f0, textvariable=codigo, width=60)
        e1.pack(side=LEFT)
        e1.bind("<KeyRelease>", caps)

        self.f2 = Frame(self.wrapper)
        self.f2.pack(pady=5, fill=X)  #-----------------------------------

        l2 = Label(self.f2, text="Cuenta Contable: ")
        l2.pack(side=LEFT)

        e2 = Entry(self.f2, textvariable=ctacontable, width=60)
        e2.pack(side=LEFT, fill=X, expand=1)

        b0 = Button(self.f2, text="Buscar", image=lupa, command=buscar)
        b0.image = lupa
        b0.pack(side=LEFT)

        self.f3 = Frame(self.wrapper)
        self.f3.pack(pady=5, fill=X)  #-----------------------------------

        self.nombre = Label(self.f3, text="Nombre: ")
        self.nombre.pack(side=LEFT)
        self.nombreE = Entry(self.f3, textvariable=nombre, state=DISABLED)
        self.nombreE.pack(side=LEFT, fill=X, expand=1)

        self.f4 = Frame(self.wrapper)
        self.f4.pack(pady=5, fill=X)  #-----------------------------------

        self.descL = Label(self.f4, text="Descripción: ")
        self.descL.pack(side=LEFT)
        self.descE = Entry(self.f4, textvariable=desc)
        self.descE.pack(side=LEFT, fill=X, expand=1)
        self.descE.bind("<KeyRelease>", caps)

        self.f5 = Frame(self.wrapper)
        self.f5.pack(pady=5, fill=X)  #-----------------------------------

        b1 = Button(self.f5,
                    text="Cargar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=cargar)
        b1.pack(side=RIGHT)

        b2 = Button(self.f5,
                    text="Agregar",
                    bg='navy',
                    foreground='white',
                    activebackground='red3',
                    activeforeground='white',
                    command=agregar)
        b2.pack(side=RIGHT)

        self.f6 = Frame(self.wrapper)
        self.f6.pack(pady=5, fill=X)  #-----------------------------------

        tree = Treeview(self.f6,
                        show="headings",
                        columns=('col1', 'col2', 'col3', 'col4'))
        tree.pack(side=LEFT, fill=X, expand=1)
        tree.column('col1', width=2, anchor='center')
        tree.column('col2', width=150, anchor='center')
        tree.column('col3', width=10, anchor='center')
        tree.column('col4', width=150, anchor='center')

        tree.heading('col1', text='Código')
        tree.heading('col2', text='Descripción')
        tree.heading('col3', text='Cta Contable')
        tree.heading('col4', text='Nombre')

        self.scroll = Scrollbar(self.f6, orient=VERTICAL, command=tree.yview)
        tree.configure(yscrollcommand=self.scroll.set)

        self.f7 = Frame(self.wrapper)
        self.f7.pack(pady=5, fill=X)  #-----------------------------------

        self.delete = Button(self.f7,
                             text="Eliminar",
                             bg='navy',
                             foreground='white',
                             activebackground='red3',
                             activeforeground='white',
                             command=borrar)
        self.delete.pack(side=RIGHT)
Ejemplo n.º 14
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global e0, e1, e2, e3, e4, e5, e6, e7, e8, CbxVlr, observaciones, scroll, tree, pdfB, add
		global cc, arrend, inmueble, codigo, tel, valor
		global Cbx, meses, mes1, mes2, tiempo, fechapago, anio, mes
		global prop, nit, tp, subtotal, iva, total
				
		#VARIABLES
		tiempo = datetime.date.today()
		anio = time.strftime("%Y")
		mes = time.strftime("%B")
		fechapago = StringVar()
		
		cc = StringVar()
		arrend = StringVar()
		
		inmueble = StringVar()
		codigo = StringVar()
		tel = StringVar()
		valor = DoubleVar()
		
		prop = StringVar()
		nit = StringVar()
		tp = StringVar()
		
		subtotal = DoubleVar()
		iva = DoubleVar()
		total = DoubleVar()
		
		mes1 = StringVar()
		mes2 = StringVar()
		meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]

		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="FACTURA INQUILINO", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#========================= WRAPPER 1 ===========================
		
		wrapper = Frame (self)
		wrapper.pack(fill='both')

		#======================= DATOS GENERALES =======================
		
		self.lf = LabelFrame(wrapper, text="Datos generales")
		self.lf.pack(side=LEFT)#-------------------------------

		self.f0 = Frame(self.lf)
		self.f0.pack(pady=5,fill=X)#---------------------------

		self.ccnitL = Label(self.f0, text='CC/Nit:')
		self.ccnitL.pack(side=LEFT)
		e0 = Entry(self.f0, textvariable=cc, width=30)
		e0.pack(side=LEFT)
		
		self.b1 = Button (self.f0, text='Buscar', command=buscar)
		self.b1.pack(side=LEFT)

		self.f1 = Frame(self.lf)
		self.f1.pack(pady=5,fill=X)#---------------------------
		
		self.nombreL = Label(self.f1, text='Nombre:')
		self.nombreL.pack(side=LEFT)
		e1 = Entry(self.f1, textvariable=arrend, width=50, state=DISABLED)
		e1.pack(side=LEFT,fill=X)

		self.f2 = Frame(self.lf)
		self.f2.pack(pady=5,fill=X)#---------------------------
		
		self.inmuebleL = Label(self.f2, text='Inmueble:')
		self.inmuebleL.pack(side=LEFT)
		e2 = Entry(self.f2, textvariable=inmueble, state=DISABLED, width=48)
		e2.pack(side=LEFT,fill=X)
		
		self.f3 = Frame(self.lf)
		self.f3.pack(pady=5,fill=X)#---------------------------
		
		self.inmuebleL = Label(self.f3, text='Código: ')
		self.inmuebleL.pack(side=LEFT)
		e3 = Entry(self.f3, textvariable=codigo, state=DISABLED, width=5)
		e3.pack(side=LEFT,fill=X)
		
		self.tel = Label(self.f3, text='Teléfono: ')
		self.tel.pack(side=LEFT)
		e4 = Entry(self.f3, textvariable=tel, state=DISABLED, width=15)
		e4.pack(side=LEFT,fill=X)
		
		self.precio = Label(self.f3, text='Arriendo $: ')
		self.precio.pack(side=LEFT)
		e5 = Entry(self.f3, textvariable=valor, state=DISABLED, width=15)
		e5.pack(side=LEFT,fill=X)
		
		#======================= DATOS PROPIETARIO =======================
		
		wrap = Frame(wrapper)
		wrap.pack(side=RIGHT)
		
		lf = LabelFrame(wrap, text="Propietario")
		lf.pack()#-------------------------
		#lf.pack_forget()#-------------------------
		
		f0 = Frame(lf)
		f0.pack(pady=5,fill=X)#---------------------------
		
		nombreL = Label(f0, text='Nombre: ')
		nombreL.pack(side=LEFT)
		e6 = Entry(f0, textvariable=prop, width=48, state=DISABLED)
		e6.pack(side=LEFT,fill=X)
		
		f1 = Frame(lf)
		f1.pack(pady=5,fill=X)#---------------------------

		ccnitL = Label(f1, text='CC/Nit: ')
		ccnitL.pack(side=LEFT)
		e7 = Entry(f1, textvariable=nit, state=DISABLED, width=48)
		e7.pack(side=LEFT)
		
		f2 = Frame(wrap)
		f2.pack(pady=5,fill=X)#---------------------------
		
		self.lb = Label(f2, text=None)
		self.lb.pack(side=LEFT)
		
		f3 = Frame(wrap)
		f3.pack(pady=5,fill=X)#---------------------------
		
		"""
		self.inmuebleL = Label(f2, text='Tipo Persona: ')
		self.inmuebleL.pack(side=LEFT)
		e8 = Entry(f2, textvariable=tp, state=DISABLED, width=40)
		e8.pack(side=LEFT,fill=X)
		"""
		
		l = Label(f3, text='SubTotal ')
		l.pack(side=LEFT)
		e8 = Entry(f3, textvariable=subtotal, state=DISABLED, width=12)
		e8.pack(side=LEFT,fill=X)
		
		l = Label(f3, text='IVA ')
		l.pack(side=LEFT)
		e9 = Entry(f3, textvariable=iva, state=DISABLED, width=12)
		e9.pack(side=LEFT,fill=X)
		
		l = Label(f3, text='Total ')
		l.pack(side=LEFT)
		e10 = Entry(f3, textvariable=total, state=DISABLED, width=12)
		e10.pack(side=LEFT,fill=X)
		
		f4 = Frame(wrap)
		f4.pack(pady=5,fill=X)#---------------------------
		
		#========================= FACTURACIÓN =========================
		
		self.lf1 = LabelFrame(self, text="Periodo a facturar")
		self.lf1.pack(anchor=W,pady=5,fill=X)#-------------------------

		self.f2 = Frame(self.lf1)
		self.f2.pack(pady=5,fill=X)#---------------------------

		self.mesiniL = Label(self.f2, text='Mes inicial:')
		self.mesiniL.pack(padx=5,side=LEFT)

		CbxVlr = Combobox(self.f2, textvariable=mes1, values=meses, width=10, state=DISABLED)
		CbxVlr.set(mes)
		CbxVlr.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)
	
		self.yeariniL = Label(self.f2, text='Año:')
		self.yeariniL.pack(side=LEFT)
		self.yeariniE = Entry(self.f2, textvariable=fechapago, width=8, state=DISABLED)
		fechapago.set(anio)
		self.yeariniE.pack(side=LEFT)

		self.mesfinL = Label(self.f2, text='Mes final:')
		self.mesfinL.pack(padx=5,side=LEFT)

		self.mesfinCbx = Combobox(self.f2, textvariable=mes2, values=meses, width=10)
		self.mesfinCbx.set(mes)
		self.mesfinCbx.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)

		self.yearfinL = Label(self.f2, text='Año:')
		self.yearfinL.pack(side=LEFT)
		self.yearfinE = Entry(self.f2, textvariable=fechapago, width=8)
		fechapago.set(anio)
		self.yearfinE.pack(side=LEFT)

		self.emptyL = Label(self.f2)###VACIO###
		self.emptyL.pack(padx=5, side=LEFT)
		
		pdfB = Button(self.f2, text="Facturar", command=agregar, state=DISABLED)
		pdfB.pack(side=LEFT)

		#========================== TREEVIEW ===========================
		
		self.f3 = Frame(self)
		self.f3.pack(pady=5,fill=X)#------------------------------------
		
		tree = Treeview(self.f3, height=4, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		
		tree.column('col1', width=250, anchor='center')
		tree.column('col2', width=5, anchor='center')
		
		tree.heading('col1', text='Descripción')
		tree.heading('col2', text='Valor')
		
		scroll = Scrollbar(self.f3,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=scroll.set)
		tree.bind("<Delete>", borrar)
		
		#======================== OBSERVACIONES ========================

		self.f4 = Frame(self)
		self.f4.pack(pady=5,fill=X)#--------------------

		self.notesL = Label(self.f4, text='Observaciones:')
		self.notesL.pack(side=LEFT)

		self.f5 = Frame(self)
		self.f5.pack(pady=5,fill=X)#-------------------

		observaciones = Text(self.f5, height=5)
		observaciones.pack(fill=X, side=LEFT, expand=1)
		
		#=========================== BOTONES ===========================
		
		footer = Frame(self)
		footer.pack()#-------------------------------
		
		clean = Button(footer, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cancelar)
		clean.pack(side=RIGHT)
		
		add = Button(footer, text='Grabar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=grabar, state=DISABLED)
		add.pack(side=RIGHT)
Ejemplo n.º 15
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

		global codigo, ctacontable, nombre, desc, tree
		
		lupa = PhotoImage(file='img/lupa.png')
		
		codigo = StringVar()
		ctacontable = StringVar()
		nombre = StringVar()
		desc = StringVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="CONCEPTO DE GASTOS", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (self.f0, text="Código:")
		l1.pack(side=LEFT)
		e1 = Entry (self.f0, textvariable=codigo, width=60)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		
		self.f2 = Frame(self.wrapper)
		self.f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (self.f2, text="Cuenta Contable: ")
		l2.pack(side=LEFT)
		
		e2 = Entry (self.f2, textvariable=ctacontable, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		
		b0 = Button (self.f2, text="Buscar", image=lupa, command=buscar)
		b0.image=lupa
		b0.pack(side=LEFT)
		
		self.f3 = Frame(self.wrapper)
		self.f3.pack(pady=5, fill=X)#-----------------------------------
		
		self.nombre = Label (self.f3, text="Nombre: ")
		self.nombre.pack(side=LEFT)
		self.nombreE = Entry (self.f3, textvariable=nombre, state=DISABLED)
		self.nombreE.pack(side=LEFT, fill=X, expand=1)
		
		self.f4 = Frame(self.wrapper)
		self.f4.pack(pady=5, fill=X)#-----------------------------------
		
		self.descL = Label (self.f4, text="Descripción: ")
		self.descL.pack(side=LEFT)
		self.descE = Entry (self.f4, textvariable=desc)
		self.descE.pack(side=LEFT, fill=X, expand=1)
		self.descE.bind("<KeyRelease>", caps)
		
		self.f5 = Frame(self.wrapper)
		self.f5.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (self.f5, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (self.f5, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		self.f6 = Frame(self.wrapper)
		self.f6.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(self.f6, show="headings", columns=('col1','col2', 'col3', 'col4'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=2, anchor='center')
		tree.column('col2', width=150, anchor='center')
		tree.column('col3', width=10, anchor='center')
		tree.column('col4', width=150, anchor='center')
		
		tree.heading('col1', text='Código')
		tree.heading('col2', text='Descripción')
		tree.heading('col3', text='Cta Contable')
		tree.heading('col4', text='Nombre')
		
		self.scroll = Scrollbar(self.f6,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)
		
		self.f7 = Frame(self.wrapper)
		self.f7.pack(pady=5, fill=X)#-----------------------------------
		
		self.delete = Button (self.f7, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		self.delete.pack(side=RIGHT)
Ejemplo n.º 16
0
    def show(frame, iterator):
        """Выводит на экран выборку, заданную в iterator"""

        scrollbar = Scrollbar(frame)
        tree = Treeview(frame, selectmode='none', padding=3,
                                    style='Custom.Treeview', height=REPORT_HEIGHT,
                                    yscrollcommand=scrollbar.set)
        tree.pack(side=LEFT, fill=BOTH, expand=YES)
        scrollbar.config(command=tree.yview)
        scrollbar.pack(side=LEFT, fill=Y)

        tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT))
        tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT),
                                                           background='#f5f5ff')
        tree.tag_configure('red1', font=('Verdana', FONT_SIZE_REPORT),
                                                               foreground='red')
        tree.tag_configure('red2', font=('Verdana', FONT_SIZE_REPORT),
                                         background='#f5f5ff', foreground='red')
        tree.tag_configure('grey1', font=('Verdana', FONT_SIZE_REPORT),
                                                              foreground='#dddddd')
        tree.tag_configure('grey2', font=('Verdana', FONT_SIZE_REPORT),
                                        background='#f5f5ff', foreground='#dddddd')

        Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2)

        columns = ['#' + str(x + 1) for x in range(4)]
        tree.configure(columns=columns)

        for q in range(len(header)):
            tree.heading('#%d' % (q + 1), text=header[q], anchor='w')
            tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1],
                                                                     anchor='w')
        tree.heading('#0', text='', anchor='w')
        tree.column('#0', width=0, anchor='w', minwidth=0)

        flag = True
        for item in iterator:
            if not item.calculation:
                col = []
                col.append(add_s(item.cathegory.name if item.cathegory
                                                                 else u'-Нет-'))
                col.append(add_s(item.name))
                storage = queries.items_in_storage(item)
                col.append(add_s(storage))
                col.append(add_s(item.measure))
                if int(storage) > 0:
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='1')
                elif storage == '0':
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='grey2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='grey1')
                else:
                    flag = not flag
                    if flag:
                        tree.insert('', 'end', text='', values=col, tag='red2')
                    else:
                        tree.insert('', 'end', text='', values=col, tag='red1')
Ejemplo n.º 17
0
class Multicolumn_Listbox(object):
    _style_index = 0

    class List_Of_Rows(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox

        def data(self, index):
            return self._multicolumn_listbox.row_data(index)

        def get(self, index):
            return Row(self._multicolumn_listbox, index)

        def insert(self, data, index=None):
            self._multicolumn_listbox.insert_row(data, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_row(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_row(index, data)

        def select(self, index):
            self._multicolumn_listbox.select_row(index)

        def deselect(self, index):
            self._multicolumn_listbox.deselect_row(index)

        def set_selection(self, indices):
            self._multicolumn_listbox.set_selection(indices)

        def __getitem__(self, index):
            return self.get(index)

        def __setitem__(self, index, value):
            return self._multicolumn_listbox.update_row(index, value)

        def __delitem__(self, index):
            self._multicolumn_listbox.delete_row(index)

        def __len__(self):
            return self._multicolumn_listbox.number_of_rows

    class List_Of_Columns(object):
        def __init__(self, multicolumn_listbox):
            self._multicolumn_listbox = multicolumn_listbox

        def data(self, index):
            return self._multicolumn_listbox.get_column(index)

        def get(self, index):
            return Column(self._multicolumn_listbox, index)

        def delete(self, index):
            self._multicolumn_listbox.delete_column(index)

        def update(self, index, data):
            self._multicolumn_listbox.update_column(index, data)

        def __getitem__(self, index):
            return self.get(index)

        def __setitem__(self, index, value):
            return self._multicolumn_listbox.update_column(index, value)

        def __delitem__(self, index):
            self._multicolumn_listbox.delete_column(index)

        def __len__(self):
            return self._multicolumn_listbox.number_of_columns

    def __init__(self,
                 master,
                 columns,
                 data=None,
                 command=None,
                 sort=True,
                 select_mode=None,
                 heading_anchor=CENTER,
                 cell_anchor=W,
                 style=None,
                 height=None,
                 padding=None,
                 adjust_heading_to_content=False,
                 striped_rows=None,
                 selection_background=None,
                 selection_foreground=None,
                 field_background=None,
                 heading_font=None,
                 heading_background=None,
                 heading_foreground=None,
                 cell_pady=2,
                 cell_background=None,
                 cell_foreground=None,
                 cell_font=None,
                 headers=True,
                 right_click_command=None):

        self._striped_rows = striped_rows

        self._columns = columns

        self._number_of_rows = 0
        self._number_of_columns = len(columns)

        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)

        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview" % self._style_index
            self._style_index += 1
        else:
            style_name = style

        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]

        if selection_foreground is not None:
            style_map["foreground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(cell_font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(cell_font) == 2:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1])

                    elif len(cell_font) == 3:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1],
                                         weight=cell_font[2])
                    else:
                        raise ValueError(
                            "Not possible more than 3 values for font")

            style_config["font"] = cell_font

        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace") + cell_pady
        style_config["rowheight"] = self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height

        if padding is not None:
            treeview_kwargs["padding"] = padding

        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""

        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)
        # tjw Scrollbar add
        self.scrollbar = Scrollbar(master,
                                   orient=VERTICAL,
                                   command=self.interior.yview)
        self.interior.configure(yscrollcommand=self.scrollbar.set)
        self.scrollbar.grid(row=1, column=len(columns), sticky='NSE')
        self.interior.grid(row=1, column=0)
        #master.grid_columnconfigure(0, weight=1)
        #master.grid_columnconfigure(1, weight=1)

        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        if right_click_command is not None:
            self._right_click_command = right_click_command
            self.interior.bind("<Button-3>", self._on_right_click)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(
                    i,
                    text=columns[i],
                    anchor=heading_anchor,
                    command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i,
                                      text=columns[i],
                                      anchor=heading_anchor)

            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)

        if data is not None:
            for row in data:
                self.insert_row(row)

    @property
    def row_height(self):
        return self._rowheight

    @property
    def font(self):
        return self._cell_font

    def configure_column(self,
                         index,
                         width=None,
                         minwidth=None,
                         anchor=None,
                         stretch=None):
        kwargs = {}
        for config_name in ("width", "anchor", "stretch", "minwidth"):
            config_value = locals()[config_name]
            if config_value is not None:
                kwargs[config_name] = config_value

        self.interior.column('#%s' % (index + 1), **kwargs)

    def row_data(self, index):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        return self.item_ID_to_row_data(item_ID)

    def update_row(self, index, data):
        try:
            item_ID = self.interior.get_children()[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        if len(data) == len(self._columns):
            self.interior.item(item_ID, values=data)
        else:
            raise ValueError("The multicolumn listbox has only %d columns" %
                             self._number_of_columns)

    def delete_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.delete(item_ID)
        self._number_of_rows -= 1

        if self._striped_rows:
            for i in range(index, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i + 1],
                                            background=self._striped_rows[i %
                                                                          2])

    def insert_row(self, data, index=None):
        if len(data) != self._number_of_columns:
            raise ValueError("The multicolumn listbox has only %d columns" %
                             self._number_of_columns)

        if index is None:
            index = self._number_of_rows - 1

        item_ID = self.interior.insert('', index, values=data)
        self.interior.item(item_ID, tags=item_ID)

        self._number_of_rows += 1

        if self._striped_rows:
            list_of_items = self.interior.get_children()

            self.interior.tag_configure(item_ID,
                                        background=self._striped_rows[index %
                                                                      2])

            for i in range(index + 1, self._number_of_rows):
                self.interior.tag_configure(list_of_items[i],
                                            background=self._striped_rows[i %
                                                                          2])

    def column_data(self, index):
        return [
            self.interior.set(child_ID, index)
            for child_ID in self.interior.get_children('')
        ]

    def update_column(self, index, data):
        for i, item_ID in enumerate(self.interior.get_children()):
            data_row = self.item_ID_to_row_data(item_ID)
            data_row[index] = data[i]

            self.interior.item(item_ID, values=data_row)

        return data

    def clear(self):
        # Another possibility:
        #  self.interior.delete(*self.interior.get_children())

        for row in self.interior.get_children():
            self.interior.delete(row)

        self._number_of_rows = 0

    def update(self, data):
        self.clear()

        for row in data:
            self.insert_row(row)

    def focus(self, index=None):
        if index is None:
            return self.interior.item(self.interior.focus())
        else:
            item = self.interior.get_children()[index]
            self.interior.focus(item)

    def state(self, state=None):
        if state is None:
            return self.interior.state()
        else:
            self.interior.state(state)

    @property
    def number_of_rows(self):
        return self._number_of_rows

    @property
    def number_of_columns(self):
        return self._number_of_columns

    def toogle_selection(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_toggle(item_ID)

    def select_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_add(item_ID)

    def deselect_row(self, index):
        list_of_items = self.interior.get_children()

        try:
            item_ID = list_of_items[index]
        except IndexError:
            raise ValueError("Row index out of range: %d" % index)

        self.interior.selection_remove(item_ID)

    def deselect_all(self):
        self.interior.selection_remove(self.interior.selection())

    def set_selection(self, indices):
        list_of_items = self.interior.get_children()

        self.interior.selection_set(" ".join(list_of_items[row_index]
                                             for row_index in indices))

    @property
    def selected_rows(self):
        data = []
        for item_ID in self.interior.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)

        return data

    @property
    def indices_of_selected_rows(self):
        list_of_indices = []
        for index, item_ID in enumerate(self.interior.get_children()):
            if item_ID in self.interior.selection():
                list_of_indices.append(index)

        return list_of_indices

    def delete_all_selected_rows(self):
        selected_items = self.interior.selection()
        for item_ID in selected_items:
            self.interior.delete(item_ID)

        number_of_deleted_rows = len(selected_items)
        self._number_of_rows -= number_of_deleted_rows

        return number_of_deleted_rows

    def _on_select(self, event):
        for item_ID in event.widget.selection():
            data_row = self.item_ID_to_row_data(item_ID)
            self._command(data_row)

    def _on_right_click(self, event):
        item_ID = event.widget.identify_row(event.y)
        data_row = self.item_ID_to_row_data(item_ID)
        if data_row:
            self._right_click_command(data_row)

    def item_ID_to_row_data(self, item_ID):
        item = self.interior.item(item_ID)
        return item["values"]

    @property
    def table_data(self):
        data = []

        for item_ID in self.interior.get_children():
            data_row = self.item_ID_to_row_data(item_ID)
            data.append(data_row)

        return data

    @table_data.setter
    def table_data(self, data):
        self.update(data)

    def cell_data(self, row, column):
        """Get the value of a table cell"""
        try:
            item = self.interior.get_children()[row]
        except IndexError:
            raise ValueError("Row index out of range: %d" % row)

        return self.interior.set(item, column)

    def update_cell(self, row, column, value):
        """Set the value of a table cell"""

        item_ID = self.interior.get_children()[row]

        data = self.item_ID_to_row_data(item_ID)

        data[column] = value
        self.interior.item(item_ID, values=data)

    def __getitem__(self, index):
        if isinstance(index, tuple):
            row, column = index
            return self.cell_data(row, column)
        else:
            raise Exception("Row and column indices are required")

    def __setitem__(self, index, value):
        if isinstance(index, tuple):
            row, column = index
            self.update_cell(row, column, value)
        else:
            raise Exception("Row and column indices are required")

    def bind(self, event, handler):
        self.interior.bind(event, handler)

    def sort_by(self, col, descending):
        """
        sort tree contents when a column header is clicked
        """
        # grab values to sort
        data = [(self.interior.set(child_ID, col), child_ID)
                for child_ID in self.interior.get_children('')]

        # if the data to be sorted is numeric change to float
        try:
            data = [(float(number), child_ID) for number, child_ID in data]
            # now sort the data in place
            data.sort(reverse=descending)
        except ValueError:
            # now sort the strings in place, ignoring case
            data.sort(reverse=descending, key=lambda x: x[0].lower())

        for idx, item in enumerate(data):
            self.interior.move(item[1], '', idx)

        # switch the heading so that it will sort in the opposite direction
        self.interior.heading(
            col, command=lambda col=col: self.sort_by(col, not descending))

        if self._striped_rows:
            list_of_items = self.interior.get_children('')
            for i in range(len(list_of_items)):
                self.interior.tag_configure(list_of_items[i],
                                            background=self._striped_rows[i %
                                                                          2])

    def destroy(self):
        self.interior.destroy()

    def item_ID(self, index):
        return self.interior.get_children()[index]
Ejemplo n.º 18
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		
		global codigo, descripcion, tree, busqueda, info
		global e3
		
		lupa = PhotoImage(file='img/lupa.png')
		
		codigo = StringVar()
		descripcion = StringVar()
		busqueda = StringVar()
		info = IntVar()
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="CUENTAS CONTABLES", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		#self.wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label (self.f0, text="Código:")
		l1.pack(side=LEFT)
		e1 = Entry (self.f0, textvariable=codigo, width=20)
		e1.pack(side=LEFT)
		e1.bind("<KeyRelease>", caps)
		e1.focus_set()
		
		self.f2 = Frame(self.wrapper)
		self.f2.pack(pady=5, fill=X)#-----------------------------------
		
		l2 = Label (self.f2, text="Descripción: ")
		l2.pack(side=LEFT)
		e2 = Entry (self.f2, textvariable=descripcion, width=60)
		e2.pack(side=LEFT, fill=X, expand=1)
		e2.bind("<KeyRelease>", caps)
		
		self.f3 = Frame(self.wrapper)
		self.f3.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (self.f3, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
		b1.pack(side=RIGHT)
		
		b2 = Button (self.f3, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
		b2.pack(side=RIGHT)
		
		#========================== TREEVIEW ===========================
		
		self.f4 = Frame(self.wrapper)
		self.f4.pack(pady=5, fill=X)#-----------------------------------
		
		tree = Treeview(self.f4, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=0, anchor='center')
		tree.column('col2', width=150, anchor='w')
		
		tree.heading('col1', text='Código')
		tree.heading('col2', text='Descripción')
		
		self.scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)
		
		self.f5 = Frame(self.wrapper)
		self.f5.pack(pady=5, fill=X)#-----------------------------------
		
		self.delete = Button (self.f5, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		self.delete.pack(side=RIGHT)
		
		e3 = Entry(self.f5, textvariable=busqueda)
		e3.pack(side=LEFT)
		e3.bind("<KeyRelease>", caps)
		
		b3 = Button(self.f5, text='BUSCAR', image=lupa, command=buscar)
		b3.image = lupa
		b3.pack(side=LEFT)
		
		R1 = Radiobutton(self.f5, text="Código", variable=info, value=1)
		R1.pack(side=LEFT)
		R2 = Radiobutton (self.f5, text="Desc", variable=info, value=2)
		R2.pack(side=LEFT)
		info.set(1)
Ejemplo n.º 19
0
class MainWindowUI:

# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |                                     menu bar                                                  |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                     search bar                                |
# |               |          search entry                                                 | button|
# |               +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |   treeview    |                                       |                                       |
# |               |              text area 1              |               text area 2             |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |

    # Rows
    fileTreeRow = filePathLabelsRow = 0
    searchTextRow = 1
    uniScrollbarRow = lineNumbersRow = textAreasRow = 2
    horizontalScrollbarRow = 3

    # Columns
    fileTreeCol = 0
    fileTreeScrollbarCol = 1
    leftLineNumbersCol = leftFilePathLabelsCol = 2    # should span at least two columns
    leftTextAreaCol = leftHorizontalScrollbarCol = 3
    uniScrollbarCol = 4
    rightLineNumbersCol = rightFilePathLabelsCol = 5  # should span at least two columns
    rightTextAreaCol = rightHorizontalScrollbarCol = 6

    # Colors
    whiteColor = '#ffffff'
    redColor = '#ffc4c4'
    darkredColor = '#ff8282'
    grayColor = '#dddddd'
    lightGrayColor = '#eeeeee'
    greenColor = '#c9fcd6'
    darkgreenColor = '#50c96e'
    yellowColor = '#f0f58c'
    darkYellowColor = '#ffff00'
    purpleLight = '#F5EBFC'

    def __init__(self, window):
        self.main_window = window
        self.main_window.grid_rowconfigure(self.filePathLabelsRow, weight=0)
        self.main_window.grid_rowconfigure(self.searchTextRow, weight=0)
        self.main_window.grid_rowconfigure(self.textAreasRow, weight=1)

        self.main_window.grid_columnconfigure(self.fileTreeCol, weight=0)
        self.main_window.grid_columnconfigure(self.fileTreeScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftTextAreaCol, weight=1)
        self.main_window.grid_columnconfigure(self.uniScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightTextAreaCol, weight=1)
        self.menubar = Menu(self.main_window)
        self.menus = {}
        self.text_area_font = 'TkFixedFont'

    # Center window and set its size
    def center_window(self):
        sw = self.main_window.winfo_screenwidth()
        sh = self.main_window.winfo_screenheight()

        w = 0.7 * sw
        h = 0.7 * sh

        x = (sw - w)/2
        y = (sh - h)/2
        self.main_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.main_window.minsize(int(0.3 * sw), int(0.3 * sh))

    # Menu bar
    def add_menu(self, menuName, commandList):
        self.menus[menuName] = Menu(self.menubar,tearoff=0)
        for c in commandList:
            if 'separator' in c: self.menus[menuName].add_separator()
            else: self.menus[menuName].add_command(label=c['name'], command=c['command'], accelerator=c['accelerator'] if 'accelerator' in c else '')
        self.menubar.add_cascade(label=menuName, menu=self.menus[menuName])
        self.main_window.config(menu=self.menubar)

    # Labels
    def create_file_path_labels(self):
        self.leftFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.leftFileLabel.grid(row=self.filePathLabelsRow, column=self.leftFilePathLabelsCol, columnspan=2)
        self.rightFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.rightFileLabel.grid(row=self.filePathLabelsRow, column=self.rightFilePathLabelsCol, columnspan=2)

    # Search text entry
    def create_search_text_entry(self, searchButtonCallback):
        self.searchTextDialog = SearchTextDialog(self.main_window, [self.leftFileTextArea, self.rightFileTextArea], searchButtonCallback)
        self.searchTextDialog.grid(row=self.searchTextRow, column=self.leftFilePathLabelsCol, columnspan=5, sticky=EW)

        self.searchTextDialog.grid_remove()

    # File treeview
    def create_file_treeview(self):
        self.fileTreeView = Treeview(self.main_window)
        self.fileTreeYScrollbar = Scrollbar(self.main_window, orient='vertical', command=self.fileTreeView.yview)
        self.fileTreeXScrollbar = Scrollbar(self.main_window, orient='horizontal', command=self.fileTreeView.xview)
        self.fileTreeView.configure(yscroll=self.fileTreeYScrollbar.set, xscroll=self.fileTreeXScrollbar.set)

        self.fileTreeView.grid(row=self.fileTreeRow, column=self.fileTreeCol, sticky=NS, rowspan=3)
        self.fileTreeYScrollbar.grid(row=self.fileTreeRow, column=self.fileTreeScrollbarCol, sticky=NS, rowspan=3)
        self.fileTreeXScrollbar.grid(row=self.horizontalScrollbarRow, column=self.fileTreeCol, sticky=EW)

        self.fileTreeView.tag_configure('red', background=self.redColor)
        self.fileTreeView.tag_configure('green', background=self.greenColor)
        self.fileTreeView.tag_configure('yellow', background=self.yellowColor)
        self.fileTreeView.tag_configure('purpleLight', background=self.purpleLight)

        # hide it until needed
        self.fileTreeView.grid_remove()
        self.fileTreeYScrollbar.grid_remove()
        self.fileTreeXScrollbar.grid_remove()

    # Text areas
    def create_text_areas(self):
        self.leftFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.leftFileTextArea.grid(row=self.textAreasRow, column=self.leftTextAreaCol, sticky=NSEW)
        self.leftFileTextArea.config(font=self.text_area_font)
        self.leftFileTextArea.config(wrap='none')

        self.rightFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.rightFileTextArea.grid(row=self.textAreasRow, column=self.rightTextAreaCol, sticky=NSEW)
        self.rightFileTextArea.config(font=self.text_area_font)
        self.rightFileTextArea.config(wrap='none')

        # configuring highlight tags
        self.leftFileTextArea.tag_configure('red', background=self.redColor)
        self.leftFileTextArea.tag_configure('darkred', background=self.darkredColor)
        self.leftFileTextArea.tag_configure('gray', background=self.grayColor)
        self.leftFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('green', background=self.greenColor)
        self.rightFileTextArea.tag_configure('darkgreen', background=self.darkgreenColor)
        self.rightFileTextArea.tag_configure('gray', background=self.grayColor)
        self.rightFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('purpleLight', background=self.purpleLight)

        # disable the text areas
        self.leftFileTextArea.config(state=DISABLED)
        self.rightFileTextArea.config(state=DISABLED)

    # Line numbers
    def create_line_numbers(self):
        self.leftLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.leftLinenumbers.grid(row=self.lineNumbersRow, column=self.leftLineNumbersCol, sticky=NS)
        self.leftLinenumbers.config(font=self.text_area_font)
        self.leftLinenumbers.tag_configure('line', justify='right')

        self.rightLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.rightLinenumbers.grid(row=self.lineNumbersRow, column=self.rightLineNumbersCol, sticky=NS)
        self.rightLinenumbers.config(font=self.text_area_font)
        self.rightLinenumbers.tag_configure('line', justify='right')

        # disable the line numbers
        self.leftLinenumbers.config(state=DISABLED)
        self.rightLinenumbers.config(state=DISABLED)

    # Scroll bars
    def scrollBoth(self, action, position, type=None):
        self.leftFileTextArea.yview_moveto(position)
        self.rightFileTextArea.yview_moveto(position)
        self.leftLinenumbers.yview_moveto(position)
        self.rightLinenumbers.yview_moveto(position)

    def updateScroll(self, first, last, type=None):
        self.leftFileTextArea.yview_moveto(first)
        self.rightFileTextArea.yview_moveto(first)
        self.leftLinenumbers.yview_moveto(first)
        self.rightLinenumbers.yview_moveto(first)
        self.uniScrollbar.set(first, last)

    def create_scroll_bars(self):
        self.uniScrollbar = Scrollbar(self.main_window)
        self.uniScrollbar.grid(row=self.uniScrollbarRow, column=self.uniScrollbarCol, sticky=NS)
        self.uniScrollbar.config(command=self.scrollBoth)
        self.leftFileTextArea.config(yscrollcommand=self.updateScroll)
        self.rightFileTextArea.config(yscrollcommand=self.updateScroll)
        self.leftLinenumbers.config(yscrollcommand=self.updateScroll)
        self.rightLinenumbers.config(yscrollcommand=self.updateScroll)

        leftHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        leftHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.leftHorizontalScrollbarCol, sticky=EW)
        leftHorizontalScrollbar.config(command=self.leftFileTextArea.xview)
        self.leftFileTextArea.config(xscrollcommand=leftHorizontalScrollbar.set)

        rightHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        rightHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.rightHorizontalScrollbarCol, sticky=EW)
        rightHorizontalScrollbar.config(command=self.rightFileTextArea.xview)
        self.rightFileTextArea.config(xscrollcommand=rightHorizontalScrollbar.set)
Ejemplo n.º 20
0
class CommSearch(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")        
        self.pack()
        
        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0",minwidth=0,width=0, stretch=NO)
        self.output_box.column("Example",minwidth=0,width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item,"value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
    # Somehow calling self.onSearch() does not register last key
    # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)		
    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else: 
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms,entries,entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])

			
    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms,entries,entries_map):
            self.output_box.insert('', 'end', '', value=[self.entries_found[item].title.split('\n')[0]])
			
    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()
Ejemplo n.º 21
0
class ReciboCaja(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

		lupa = PhotoImage(file='img/lupa.png')
		
		#VARIABLES
		tcontrato = ['Vivienda', 'Comercial']
		aplica = StringVar()
		
		#WIDGETS
		
		#========================= HEADER ===========================
		
		self.header = Label(self, text="RECIBO DE CAJA", font="bold")
		self.header.pack(pady=20, side=TOP)
		
		#========================== WRAPPER ==========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		#self.wrapper.pack(side=LEFT, fill=Y)#Este ubica el forma a la IZA
		
		#================ NOTEBOOK =============>
		
		self.nb = Notebook(self.wrapper)
		
		#-----------------------> TAB 1
		
		self.tab1 = Frame (self.nb)
		self.tab1.pack()
		
		self.f0 = Frame(self.tab1)#-------------------------------------
		self.f0.pack(pady=5,fill=X)

		self.R1 = Radiobutton(self.f0, text="Arrendatario", variable=aplica, value='Arrendatario')
		self.R1.pack(padx=20,side=LEFT)
		self.R2 = Radiobutton (self.f0, text="Propietario", variable=aplica, value='Propietario')
		self.R2.pack(padx=20,side=LEFT)
		self.R3 = Radiobutton (self.f0, text="Tercero", variable=aplica, value='Tercero')
		self.R3.pack(padx=20,side=LEFT)
		
		self.f1 = Frame(self.tab1)#-------------------------------------
		self.f1.pack(pady=5,fill=X)
		
		self.cc = Label(self.f1, text='CC/Nit: ')
		self.cc.pack(side=LEFT)
		self.ccE = Entry(self.f1)
		self.ccE.pack(side=LEFT)
		
		self.b1 = Button(self.f1, text='Buscar', image=lupa)
		self.b1.image=lupa
		self.b1.pack(side=LEFT)

		self.f2 = Frame(self.tab1)
		self.f2.pack(pady=5,fill=X)#------------------------------------
		
		self.nombre = Label(self.f2, text='Nombre:')
		self.nombre.pack(side=LEFT)
		self.nombrE = Entry(self.f2, width=5, state=DISABLED)
		self.nombrE.pack(side=LEFT, fill=X, expand=1)
		
		self.f3 = Frame(self.tab1)
		self.f3.pack(pady=5,fill=X)#------------------------------------
		
		self.inmueble = Label(self.f3, text='Inmueble:')
		self.inmueble.pack(side=LEFT)
		
		self.inmuebleCbx = Combobox(self.f3, values=NONE, width=10)
		self.inmuebleCbx.set('')
		self.inmuebleCbx.pack(side=LEFT, fill=X, expand=1)
		
		self.b2 = Button(self.f3, text='Agregar', image=lupa)
		self.b2.image=lupa
		self.b2.pack(side=LEFT)
		
		self.f4 = Frame(self.tab1)
		self.f4.pack(pady=5,fill=X)#------------------------------------
		
		self.fpago = Label(self.f4, text='Forma de Pago:')
		self.fpago.pack(side=LEFT)
		
		self.fpagoCbx = Combobox(self.f4, values=NONE, width=10)
		self.fpagoCbx.set('')
		self.fpagoCbx.pack(side=LEFT)
		
		self.b3 = Button(self.f4, text='Crear novedad', state=DISABLED)
		self.b3.pack(side=LEFT)

		#========================== TREEVIEW ===========================
		
		self.f5 = Frame(self.tab1)
		self.f5.pack(pady=5,fill=X)#------------------------------------
		
		self.tree = Treeview(self.f5, height=4, show="headings", columns=('col1','col2','col3'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=20, anchor='center')
		self.tree.column('col2', width=200, anchor='center')
		self.tree.column('col3', width=10, anchor='center')
		
		self.tree.heading('col1', text='CC')
		self.tree.heading('col2', text='Descripción')
		self.tree.heading('col3', text='Valor')
		
		self.scroll = Scrollbar(self.f3,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)

		self.f6 = Frame(self.tab1)
		self.f6.pack(pady=5,fill=X)#--------------------

		self.notesL = Label(self.f6, text='Observaciones:')
		self.notesL.pack(side=LEFT)

		self.f7 = Frame(self.tab1)
		self.f7.pack(pady=5,fill=X)#-------------------

		self.notesT = Text(self.f7, height=5)
		self.notesT.pack(fill=X, side=LEFT, expand=1)
		
		#-----------------------> TAB 2
		
		self.tab2 = Frame (self.nb)
		self.tab2.pack()
		
		#-----------------------> TAB 3
		
		self.tab3 = Frame (self.nb)
		self.tab3.pack()
	
		#---------------------------------------------------------------
		
		self.nb.add (self.tab1, text="Datos Generales")
		self.nb.add(self.tab2, text="Referencia de Pago", state=DISABLED)
		self.nb.add(self.tab3, text="Referencias Bancarias", state=DISABLED)
		
		self.nb.pack()
		
		#---------------------------------------------------------------
		
		self.fBtn = Frame(self.wrapper)
		self.fBtn.pack()#-------------------------------
	
		self.queryB = Button(self.fBtn, text='Consultar')
		self.queryB.pack(side=RIGHT)
		self.deleteB = Button(self.fBtn, text='Borrar')
		self.deleteB.pack(side=RIGHT)
		self.updateB = Button(self.fBtn, text='Actualizar')
		self.updateB.pack(side=RIGHT)
		self.addB = Button(self.fBtn, text='Agregar')
		self.addB.pack(side=RIGHT)
		
		#========================= ASIDE ===========================
		"""
Ejemplo n.º 22
0
class MainWindowUI:

# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |                                     menu bar                                                  |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                     search bar                                |
# |               |          search entry                                                 | button|
# |               +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |   treeview    |                                       |                                       |
# |               |              text area 1              |               text area 2             |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# |               |                                       |                                       |
# +-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
# |   1   |   2   |   3   |   4   |   5   |   6   |   7   |   8   |   9   |  10   |  11   |  12   |

    # Rows
    fileTreeRow = filePathLabelsRow = 0
    searchTextRow = 1
    uniScrollbarRow = lineNumbersRow = textAreasRow = 2
    horizontalScrollbarRow = 3

    # Columns
    fileTreeCol = 0
    fileTreeScrollbarCol = 1
    leftLineNumbersCol = leftFilePathLabelsCol = 2    # should span at least two columns
    leftTextAreaCol = leftHorizontalScrollbarCol = 3
    uniScrollbarCol = 4
    rightLineNumbersCol = rightFilePathLabelsCol = 5  # should span at least two columns
    rightTextAreaCol = rightHorizontalScrollbarCol = 6

    # Colors
    whiteColor = '#ffffff'
    redColor = '#ffc4c4'
    darkredColor = '#ff8282'
    grayColor = '#dddddd'
    lightGrayColor = '#eeeeee'
    greenColor = '#c9fcd6'
    darkgreenColor = '#50c96e'
    yellowColor = '#f0f58c'
    darkYellowColor = '#ffff00'

    def __init__(self, window):
        self.main_window = window
        self.main_window.grid_rowconfigure(self.filePathLabelsRow, weight=0)
        self.main_window.grid_rowconfigure(self.searchTextRow, weight=0)
        self.main_window.grid_rowconfigure(self.textAreasRow, weight=1)

        self.main_window.grid_columnconfigure(self.fileTreeCol, weight=0)
        self.main_window.grid_columnconfigure(self.fileTreeScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.leftTextAreaCol, weight=1)
        self.main_window.grid_columnconfigure(self.uniScrollbarCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightLineNumbersCol, weight=0)
        self.main_window.grid_columnconfigure(self.rightTextAreaCol, weight=1)
        self.menubar = Menu(self.main_window)
        self.menus = {}
        self.text_area_font = 'TkFixedFont'

    # Center window and set its size
    def center_window(self):
        sw = self.main_window.winfo_screenwidth()
        sh = self.main_window.winfo_screenheight()

        w = 0.7 * sw
        h = 0.7 * sh

        x = (sw - w)/2
        y = (sh - h)/2
        self.main_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.main_window.minsize(int(0.3 * sw), int(0.3 * sh))

    # Menu bar
    def add_menu(self, menuName, commandList):
        self.menus[menuName] = Menu(self.menubar,tearoff=0)
        for c in commandList:
            if 'separator' in c: self.menus[menuName].add_separator()
            else: self.menus[menuName].add_command(label=c['name'], command=c['command'], accelerator=c['accelerator'] if 'accelerator' in c else '')
        self.menubar.add_cascade(label=menuName, menu=self.menus[menuName])
        self.main_window.config(menu=self.menubar)

    # Labels
    def create_file_path_labels(self):
        self.leftFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.leftFileLabel.grid(row=self.filePathLabelsRow, column=self.leftFilePathLabelsCol, columnspan=2)
        self.rightFileLabel = Label(self.main_window, anchor='center', width=1000, background=self.lightGrayColor)
        self.rightFileLabel.grid(row=self.filePathLabelsRow, column=self.rightFilePathLabelsCol, columnspan=2)

    # Search text entnry
    def create_search_text_entry(self, searchButtonCallback):
        self.searchTextDialog = SearchTextDialog(self.main_window, [self.leftFileTextArea, self.rightFileTextArea], searchButtonCallback)
        self.searchTextDialog.grid(row=self.searchTextRow, column=self.leftFilePathLabelsCol, columnspan=5, sticky=EW)

        self.searchTextDialog.grid_remove()

    # File treeview
    def create_file_treeview(self):
        self.fileTreeView = Treeview(self.main_window)
        self.fileTreeYScrollbar = Scrollbar(self.main_window, orient='vertical', command=self.fileTreeView.yview)
        self.fileTreeXScrollbar = Scrollbar(self.main_window, orient='horizontal', command=self.fileTreeView.xview)
        self.fileTreeView.configure(yscroll=self.fileTreeYScrollbar.set, xscroll=self.fileTreeXScrollbar.set)

        self.fileTreeView.grid(row=self.fileTreeRow, column=self.fileTreeCol, sticky=NS, rowspan=3)
        self.fileTreeYScrollbar.grid(row=self.fileTreeRow, column=self.fileTreeScrollbarCol, sticky=NS, rowspan=3)
        self.fileTreeXScrollbar.grid(row=self.horizontalScrollbarRow, column=self.fileTreeCol, sticky=EW)

        self.fileTreeView.tag_configure('red', background=self.redColor)
        self.fileTreeView.tag_configure('green', background=self.greenColor)
        self.fileTreeView.tag_configure('yellow', background=self.yellowColor)

        # hide it until needed
        self.fileTreeView.grid_remove()
        self.fileTreeYScrollbar.grid_remove()
        self.fileTreeXScrollbar.grid_remove()

    # Text areas
    def create_text_areas(self):
        self.leftFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.leftFileTextArea.grid(row=self.textAreasRow, column=self.leftTextAreaCol, sticky=NSEW)
        self.leftFileTextArea.config(font=self.text_area_font)
        self.leftFileTextArea.config(wrap='none')

        self.rightFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.rightFileTextArea.grid(row=self.textAreasRow, column=self.rightTextAreaCol, sticky=NSEW)
        self.rightFileTextArea.config(font=self.text_area_font)
        self.rightFileTextArea.config(wrap='none')

        # configuring highlight tags
        self.leftFileTextArea.tag_configure('red', background=self.redColor)
        self.leftFileTextArea.tag_configure('darkred', background=self.darkredColor)
        self.leftFileTextArea.tag_configure('gray', background=self.grayColor)
        self.leftFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('green', background=self.greenColor)
        self.rightFileTextArea.tag_configure('darkgreen', background=self.darkgreenColor)
        self.rightFileTextArea.tag_configure('gray', background=self.grayColor)
        self.rightFileTextArea.tag_configure('search', background=self.darkYellowColor)

        # disable the text areas
        self.leftFileTextArea.config(state=DISABLED)
        self.rightFileTextArea.config(state=DISABLED)

    # Line numbers
    def create_line_numbers(self):
        self.leftLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.leftLinenumbers.grid(row=self.lineNumbersRow, column=self.leftLineNumbersCol, sticky=NS)
        self.leftLinenumbers.config(font=self.text_area_font)
        self.leftLinenumbers.tag_configure('line', justify='right')

        self.rightLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.rightLinenumbers.grid(row=self.lineNumbersRow, column=self.rightLineNumbersCol, sticky=NS)
        self.rightLinenumbers.config(font=self.text_area_font)
        self.rightLinenumbers.tag_configure('line', justify='right')

        # disable the line numbers
        self.leftLinenumbers.config(state=DISABLED)
        self.rightLinenumbers.config(state=DISABLED)

    # Scroll bars
    def scrollBoth(self, action, position, type=None):
        self.leftFileTextArea.yview_moveto(position)
        self.rightFileTextArea.yview_moveto(position)
        self.leftLinenumbers.yview_moveto(position)
        self.rightLinenumbers.yview_moveto(position)

    def updateScroll(self, first, last, type=None):
        self.leftFileTextArea.yview_moveto(first)
        self.rightFileTextArea.yview_moveto(first)
        self.leftLinenumbers.yview_moveto(first)
        self.rightLinenumbers.yview_moveto(first)
        self.uniScrollbar.set(first, last)

    def create_scroll_bars(self):
        self.uniScrollbar = Scrollbar(self.main_window)
        self.uniScrollbar.grid(row=self.uniScrollbarRow, column=self.uniScrollbarCol, sticky=NS)
        self.uniScrollbar.config(command=self.scrollBoth)
        self.leftFileTextArea.config(yscrollcommand=self.updateScroll)
        self.rightFileTextArea.config(yscrollcommand=self.updateScroll)
        self.leftLinenumbers.config(yscrollcommand=self.updateScroll)
        self.rightLinenumbers.config(yscrollcommand=self.updateScroll)

        leftHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        leftHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.leftHorizontalScrollbarCol, sticky=EW)
        leftHorizontalScrollbar.config(command=self.leftFileTextArea.xview)
        self.leftFileTextArea.config(xscrollcommand=leftHorizontalScrollbar.set)

        rightHorizontalScrollbar = Scrollbar(self.main_window, orient=HORIZONTAL)
        rightHorizontalScrollbar.grid(row=self.horizontalScrollbarRow, column=self.rightHorizontalScrollbarCol, sticky=EW)
        rightHorizontalScrollbar.config(command=self.rightFileTextArea.xview)
        self.rightFileTextArea.config(xscrollcommand=rightHorizontalScrollbar.set)
Ejemplo n.º 23
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)
		
		global info, tree
		
		#VARIABLES
		info = IntVar()
		
		#WIDGETS
		
		#========================= HEADER ===========================
		
		self.header = Label(self, text="ADMINISTRADOR DE DOCUMENTOS", font="bold")
		self.header.pack(pady=20, side=TOP)
		
		#========================= WRAPPER 1 ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=LEFT, fill=Y)

		#======================== DOCUMENTOS DE ========================
		
		self.f0 = Frame(self.wrapper)
		self.f0.pack(pady=5,fill=X)#------------------------------------

		self.lf1 = LabelFrame(self.f0, text="Documentos de")#---------->

		self.f1 = Frame(self.lf1)
		self.f1.pack(pady=5, side=LEFT)
		
		self.pR1 = Radiobutton(self.f1, text="Propietario", variable=info, value=1, command=select)
		self.pR1.grid(row=0, column=0, sticky=W)
		self.aR2 = Radiobutton (self.f1, text="Arrendatario", variable=info, value=2, command=select)
		self.aR2.grid(row=1, column=0, sticky=W)
		self.tR3 = Radiobutton (self.f1, text="Tercero", variable=info, value=3, command=select)
		self.tR3.grid(row=2, column=0, sticky=W)
		
		self.lf1.pack(side=LEFT)#<--------------------------------------
		
		#====================== FECHAS DE BÚSQUEDA =====================
		
		self.lf2 = LabelFrame(self.f0, text="Fechas de búsqueda")#------>

		self.f2 = Frame(self.lf2)
		self.f2.pack(pady=5)#---------------------------
		
		self.deL = Label(self.f2, text='De:')
		self.deL.pack(side=LEFT)
		
		self.deCbx = Combobox(self.f2, width=32)
		self.deCbx.set('')
		self.deCbx.pack(side=LEFT)
		
		self.f3 = Frame(self.lf2)
		self.f3.pack(pady=5)#---------------------------
		
		self.hastaL = Label(self.f3, text='Hasta:')
		self.hastaL.pack(side=LEFT)
		
		self.hastaCbx = Combobox(self.f3, width=30)
		self.hastaCbx.set('')
		self.hastaCbx.pack(side=LEFT)

		self.lf2.pack(side=LEFT, fill=X)#<---------------------------

		#========================= WRAPPER 2 ===========================
		
		self.wrapper2 = Frame (self.wrapper)
		self.wrapper2.pack(pady=5,fill=X)
		
		#========================= BENEFICIARIO ========================
		
		self.box1 = Frame(self.wrapper2)
		self.box1.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f4 = Frame(self.box1)
		self.f4.pack()
		
		self.l1 = Label(self.f4, text="Beneficiario")
		self.l1.pack()

		tree = Treeview(self.f4, height=7, show="headings", columns=('col1','col2'))
		tree.pack(side=LEFT, fill=X, expand=1)
		tree.column('col1', width=100, anchor='center')
		tree.column('col2', width=180, anchor='center')
		
		tree.heading('col1', text='CC')
		tree.heading('col2', text='Nombres')
		
		self.scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
		tree.configure(yscrollcommand=self.scroll.set)

		self.f5 = Frame(self.box1)#----------------------------------
		self.f5.pack()
		
		self.lf3 = LabelFrame(self.f5, text="Factura Propietario")#---->
		
		self.e1 = Entry(self.lf3, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf3, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf3, text='Visualizar').pack(side=LEFT)
		
		self.lf3.pack(side=LEFT)#<--------------------------------------
		
		#========================== FACTURAS ==========================
		
		self.box2 = Frame(self.wrapper2)
		self.box2.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f6 = Frame(self.box2)
		self.f6.pack()
		
		self.l2 = Label(self.f6, text="Facturas")
		self.l2.pack()

		self.tree = Treeview(self.f6, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f6,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f7 = Frame(self.box2)#----------------------------------
		self.f7.pack()
		
		self.lf4 = LabelFrame(self.f7, text="Factura Arrendatario")#---->
		
		self.e1 = Entry(self.lf4, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf4, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf4, text='Ver', width=5).pack(side=LEFT)
		
		self.lf4.pack(side=LEFT)#<--------------------------------------
		
		#========================== RECIBOS ==========================
		
		self.box3 = Frame(self.wrapper2)
		self.box3.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f8 = Frame(self.box3)
		self.f8.pack()
		
		self.l3 = Label(self.f8, text="Recibos de caja")
		self.l3.pack()

		self.tree = Treeview(self.f8, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f8,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f9 = Frame(self.box3)#----------------------------------
		self.f9.pack()
		
		self.lf5 = LabelFrame(self.f9, text="Recibos de caja")#---->
		
		self.e1 = Entry(self.lf5, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf5, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf5, text='Ver', width=5).pack(side=LEFT)
		
		self.lf5.pack(side=LEFT)#<--------------------------------------
		
		#===================== COMPROBANTE DE PAGO =====================
		
		self.box4 = Frame(self.wrapper2)
		self.box4.pack(side=LEFT)
		
		#---------------------------------------------------------------
		
		self.f10 = Frame(self.box4)
		self.f10.pack()
		
		self.l4 = Label(self.f10, text="Comprobantes de pago")
		self.l4.pack()

		self.tree = Treeview(self.f10, height=7, show="headings", columns=('col1','col2'))
		self.tree.pack(side=LEFT, fill=X, expand=1)
		self.tree.column('col1', width=100, anchor='center')
		self.tree.column('col2', width=100, anchor='center')
		
		self.tree.heading('col1', text='Número')
		self.tree.heading('col2', text='Valor')
		
		self.scroll = Scrollbar(self.f10,orient=VERTICAL,command=self.tree.yview)
		self.tree.configure(yscrollcommand=self.scroll.set)
		
		self.f11 = Frame(self.box4)#----------------------------------
		self.f11.pack()
		
		self.lf6 = LabelFrame(self.f11, text="Pagos")#---->
		
		self.e1 = Entry(self.lf6, width=12).pack(side=LEFT)
		self.anularCk = Checkbutton(self.lf6, text="Anular").pack(side=LEFT)
		self.viewB = Button(self.lf6, text='Ver', width=5).pack(side=LEFT)
		
		self.lf6.pack(side=LEFT)#<--------------------------------------
Ejemplo n.º 24
0
class CommSearch(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):

        self.entries_found = []

        self.parent.title("Search your command cards")
        self.style = Style()
        self.style.theme_use("default")
        self.pack()

        self.input_title = Label(self, text="Enter your command below")
        self.input_title.grid(row=0, columnspan=2)
        self.input_box = Entry(self, width=90)
        self.input_box.grid(row=1, column=0)
        self.input_box.focus()
        self.input_box.bind("<Key>", self.onUpdateSearch)
        self.search_btn = Button(self, text="Search", command=self.onSearch)
        self.search_btn.grid(row=1, column=1)
        self.output_box = Treeview(self, columns=("Example"))
        ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview)
        xsb = Scrollbar(self,
                        orient='horizontal',
                        command=self.output_box.xview)
        self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.output_box.heading('Example', text='Example', anchor='w')
        self.output_box.column("#0", minwidth=0, width=0, stretch=NO)
        self.output_box.column("Example", minwidth=0, width=785)
        self.output_box.bind("<Button-1>", self.OnEntryClick)
        self.output_box.grid(row=3, columnspan=2)
        self.selected_box = Text(self, width=110, height=19)
        self.selected_box.grid(row=4, columnspan=2)
        self.gotoadd_btn = Button(self,
                                  text="Go to Add",
                                  command=self.onGoToAdd)
        self.gotoadd_btn.grid(row=5)

    def OnEntryClick(self, event):
        try:
            item = self.output_box.selection()[0]
        except IndexError:
            pass
        entry_title = self.output_box.item(item, "value")
        for item in self.entries_found:
            if str(entry_title) == str("('" + item.title.strip('\n') + "',)"):
                self.selected_box.delete(0.1, END)
                self.selected_box.insert(END, item.text + '\n')

    def onUpdateSearch(self, key):
        # Somehow calling self.onSearch() does not register last key
        # And we need to correct "special chars"
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)

    # ...like, for instance, deleting last character
        if key.char == '\b':
            search_terms = str(self.input_box.get()[:-1])
        else:
            search_terms = str(self.input_box.get() + key.char)
        self.entries_found = []
        self.entries_found = data.Search(search_terms, entries, entries_map)
        for item in range(len(self.entries_found)):
            aux = self.output_box.insert(
                '',
                'end',
                '',
                value=[self.entries_found[item].title.split('\n')[0]])

    def onSearch(self):
        global entries, entries_map
        text_entries = ""
        for item in self.output_box.get_children():
            self.output_box.delete(item)
        search_terms = str(self.input_box.get())
        for item in data.Search(search_terms, entries, entries_map):
            self.output_box.insert(
                '',
                'end',
                '',
                value=[self.entries_found[item].title.split('\n')[0]])

    def onGoToAdd(self):
        newroot = Tk()
        newcomm = CommAdd(newroot)
        newroot.geometry("800x600+0+0")
        newroot.mainloop()