Beispiel #1
0
class SnapFrame(Frame):

    def __init__(self, parent, cb=dummy):
        Frame.__init__(self, parent)
        self.parent = parent
        self.cb = cb

        self._init_ui()

    def _cb(self, *args):
        self.cb(SNAP_DICT[self._var.get()])

    def _init_ui(self):
        self._var = StringVar()

        self.snap_combobox = Combobox(
            self, values=SNAP_DICT.keys(),
            width=5, textvariable=self._var,
            state='readonly')
        self.snap_combobox.set(SNAP_DICT.keys()[0])
        self._var.trace('w', self._cb)

        self.snap_label = Label(self, text='Snap')

        self.snap_label.pack(side=LEFT)
        self.snap_combobox.pack(side=LEFT)
Beispiel #2
0
 def _add_choice(self, frame, index, name, choices, default, option):
     self.function[-1] = lambda v: [option, v]
     label = Label(frame, text=name)
     label.grid(row=index, column=0, sticky="W", padx=10)
     field = Combobox(frame, values=choices, state="readonly")
     field.set(default)
     field.grid(row=index, column=1, sticky="WE")
     self.variables[-1] = field
Beispiel #3
0
def Reset():
    Combobox.set("")
    Tax.set("")
    SubTotal.set("")
    TotalCost.set("")
    CustomerName.set("")
    CustomerPhone.set("")
    CustomerEmail.set("")
    CustomerRef.set("")
Beispiel #4
0
def editor(): 
    """Run editor"""
    global zone_dessin     
    global grid 
    global entry_retour
    global combobox_difficulty
    global lvlList
    
    grid = Grid()
    
    # Windows
    fenetre = Tk()

    fenetre.geometry("500x525")
    fenetre.title("Editeur Hanjie")
    fenetre.resizable(width=False, height=False)

    # Canvas
    zone_dessin = Canvas(fenetre,width=500,height=500, bg="white")
    zone_dessin.place(x=0,y=0) 
    Initialisation()
    zone_dessin.bind("<Button-1>", Swap)

    # Entry
    default_text = StringVar()
    entry_retour = Entry(fenetre,width=20,textvariable=default_text)
    default_text.set("Level name...")
    entry_retour.place(x=2,y=503)

    # Save Button
    button_save = Button(fenetre,text="Save", width=8,height=1, command = But_Save)
    button_save.place(x=130,y=500)

    # Load Button
    button_load = Button(fenetre,text="Load", width=8,height=1, command = But_Load)
    button_load.place(x=200,y=500)

    # Reset Button
    button_load = Button(fenetre,text="Reset", width=8,height=1, command = But_Reset)
    button_load.place(x=270,y=500)

    # Difficulty Combobox
    lvlSelect = StringVar()
    lvlList = ('LVL 1', 'LVL 2', 'LVL 3', 'LVL 4', 'LVL 5')
    combobox_difficulty = Combobox(fenetre, values = lvlList, state = 'readonly')    
    combobox_difficulty.set(lvlList[0])
    combobox_difficulty.place(x=340,y=502)

    fenetre.mainloop()
Beispiel #5
0
class PreferencesDialog(Dialog):
    def __init__(self, parent, title, font, size):
        self._master = parent
        self.result = False
        self.font = font
        self.size = size
        Dialog.__init__(self, parent, title)

    def body(self, master):
        self._npFrame = LabelFrame(master, text='Annotation window text')
        self._npFrame.pack(fill=X)
        self._fontFrame = Frame(self._npFrame, borderwidth=0)
        self._fontLabel = Label(self._fontFrame, text='Font:', width=5)
        self._fontLabel.pack(side=LEFT, padx=3)
        self._fontCombo = Combobox(self._fontFrame,
                                   values=sorted(families()),
                                   state='readonly')
        self._fontCombo.pack(side=RIGHT, fill=X)
        self._sizeFrame = Frame(self._npFrame, borderwidth=0)
        self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5)
        self._sizeLabel.pack(side=LEFT, padx=3)
        self._sizeCombo = Combobox(self._sizeFrame,
                                   values=range(8, 15),
                                   state='readonly')
        self._sizeCombo.pack(side=RIGHT, fill=X)
        self._fontFrame.pack()
        self._sizeFrame.pack()
        self._npFrame.pack(fill=X)
        self._fontCombo.set(self.font)
        self._sizeCombo.set(self.size)

    def apply(self):
        self.font = self._fontCombo.get()
        self.size = self._sizeCombo.get()
        self.result = True

    def cancel(self, event=None):
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()
Beispiel #6
0
class PreferencesDialog(Dialog):
    def __init__(self, parent, title, font, size):
        self._master = parent
        self.result = False
        self.font = font
        self.size = size
        Dialog.__init__(self, parent, title)

    def body(self, master):
        self._npFrame = LabelFrame(master, text='Annotation window text')
        self._npFrame.pack(fill=X)
        self._fontFrame = Frame(self._npFrame, borderwidth=0)
        self._fontLabel = Label(self._fontFrame, text='Font:', width=5)
        self._fontLabel.pack(side=LEFT, padx=3)
        self._fontCombo = Combobox(self._fontFrame, values=sorted(families()),
                                   state='readonly')
        self._fontCombo.pack(side=RIGHT, fill=X)
        self._sizeFrame = Frame(self._npFrame, borderwidth=0)
        self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5)
        self._sizeLabel.pack(side=LEFT, padx=3)
        self._sizeCombo = Combobox(self._sizeFrame, values=range(8,15),
                                   state='readonly')
        self._sizeCombo.pack(side=RIGHT, fill=X)
        self._fontFrame.pack()
        self._sizeFrame.pack()
        self._npFrame.pack(fill=X)
        self._fontCombo.set(self.font)
        self._sizeCombo.set(self.size)

    def apply(self):
        self.font = self._fontCombo.get()
        self.size = self._sizeCombo.get()
        self.result = True

    def cancel(self, event=None):
        if self.parent is not None:
           self.parent.focus_set()
        self.destroy()
Beispiel #7
0
class MyEntry:
#Класс для уменьшений объёма кода однотипных элементов для ввода параметров.
    def __init__(self, place_class, string_class, DefaultValue, choise_class = False, button_add = False):
#При создании принимается место прикрепления виджета и строковое значение для надписи.
# A string value to add a combobox or a button could be also inputed.

        def button_finfo():
            messagebox.showinfo(locale(u"ui_iftxt", Settingz["str_langu"]), button_add)
# Here it is a function to show information window.

        self.frame_class = Frame(place_class)
        self.frame_class.pack(side = TOP, fill = BOTH)
#Внутри – рамка для виджетов, растягивается по ширине окна.
        self.label_class = Label(self.frame_class, text = string_class)
        self.label_class.pack(side = LEFT)
#В ней – надписи для описания вводимых значений выровнены по левому краю.
        self.entry_class = Entry(self.frame_class, width = 15)
        self.entry_class.pack(side = RIGHT)
        self.entry_class.insert(0, DefaultValue)
#И элементы для ввода значений шириной в 15 знаков выровнены по правому краю.
        if choise_class:
            self.box_class = Combobox(self.frame_class, values = choise_class, width = 2)
            self.box_class.set(choise_class[0])
            self.box_class.pack(side = RIGHT)
        elif button_add:
            self.button_class = Button(self.frame_class, text = u"?", command = button_finfo, width = -1)
            self.button_class.pack(side = RIGHT)
# The combobox widget or the button will be created if it is set.

    def get(self):
        return(self.entry_class.get())
#Метод .get() передаётся от элемента для ввода объекту описываемого класса.
    def getbox(self):
        if self.box_class.get() in ["+", "~"]:
            return(True)
        else:
            return(False)
Beispiel #8
0
class PanelPerfilGui:
    def __init__(self, master, name):
        self.frameMenu = Frame(master, background="#B4CDCD", pady=5)
        self.frameMenu.pack(side=TOP, fill=X)
        self.setPerfil(name)

    def setPerfil(self, name):
        global img
        img_ = Image.open("Images/profile.png")
        img_.thumbnail((80, 80), Image.ANTIALIAS)
        img = ImageTk.PhotoImage(img_)

        Label(self.frameMenu,
              foreground="#66CD00",
              background="#B4CDCD",
              font=("Arial", 12, "bold"),
              image=img,
              compound=LEFT).pack(side=LEFT)
        self.cb = Combobox(self.frameMenu, width=18)
        self.cb.pack(side=LEFT, fill=X)
        values = ("Israel Gomes", "Andreza Dantas", "Sandra Noronha")
        self.cb.config(value=values)
        self.cb.config(state="readonly", style="C.TCombobox")
        self.cb.set(values[0])
Beispiel #9
0
	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)
Beispiel #10
0
class NewCustomerDialog(Dialog):
    def __init__(self, master, customers, refresh, edit=False, class_=None, relx=0.5, rely=0.3):
        if edit:
            self.title = "Edit Customer"
        else:
            self.title = "New Customer"

        self.refresh = refresh

        Dialog.__init__(self, master, self.title,
                        class_, relx, rely)
        self.customers = customers

        self.fname = StringVar()
        self.lname = StringVar()
        self.mname = StringVar()
        self.payment = StringVar()
        self.date = StringVar()
        self.close = False

        self.payment.set("Drop In")

        self.edit = edit

        self.new_customer_name = None

    def show(self, line=None):
        '''
        allows preset values
        '''
        self.setup() #base class setup

        self.frame = Frame(self.root)

        # blow out the field every time this is created
        if not self.edit: self.date.set(date.today().strftime("%m/%d/%Y"))
        
        ### dialog content        
        Label(self.frame, text="First Name: ").grid(row=0, sticky=W, ipady=2, pady=2)
        Label(self.frame, text="Middle Initial: ").grid(row=1, sticky=W, ipady=2, pady=2)
        Label(self.frame, text="Last Name: ").grid(row=2, sticky=W, ipady=2, pady=2)
        Label(self.frame, text="Customer Type: ").grid(row=3, sticky=W, ipady=2, pady=2)
        Label(self.frame, text="Date (mm/dd/yyyy): ").grid(row=4, sticky=W, ipady=2, pady=2)

        self.fname_en = Entry(self.frame, width=30, textvariable=self.fname)
        self.mname_en = Entry(self.frame, width=30, textvariable=self.mname)
        self.lname_en = Entry(self.frame, width=30, textvariable=self.lname)
        self.payment_cb = Combobox(self.frame, textvariable=self.payment, width=27,
                                   values=("Drop In", "Punch Card", "Monthly", "Inactive"))
        self.payment_cb.set("Drop In")
        self.date_en = Entry(self.frame, width=30, textvariable=self.date)

        Frame(self.frame, width=5).grid(row=0,column=1,sticky=W)
        
        self.fname_en.grid(row=0,column=2,columnspan=2,sticky=W)
        self.mname_en.grid(row=1,column=2,columnspan=2,sticky=W)
        self.lname_en.grid(row=2,column=2,columnspan=2,sticky=W)
        self.payment_cb.grid(row=3,column=2,columnspan=2,sticky=W)
        self.date_en.grid(row=4,column=2,columnspan=2,sticky=W)
        
        ### buttons
        Button(self.frame, text='Cancel', width=10,
               command=self.wm_delete_window).grid(row=5, column=2, sticky=W, padx=10, pady=3)
        Button(self.frame, text='Submit', width=10,
               command=self.add_customer).grid(row=5, column=3, sticky=W)
        self.frame.pack(padx=10, pady=10)

        self.root.bind("<Return>", self.add_customer)
        self.fname_en.focus_set()

        if line: #preset values
            self.fname.set(line[1])
            self.mname.set(line[2])
            self.lname.set(line[0])
            self.payment_cb.set(line[3])
            self.date.set(line[4].strftime("%m/%d/%Y"))
        
        ### enable from base class
        self.enable()

    def add_customer(self, event=None):
        # validate and show errors
        if self.fname.get() == '':
            showerror("Error!", "First name field blank!")
        elif self.lname.get() == '':
            showerror("Error!", "Last name field blank!")
        elif self.mname.get() == '':
            showerror("Error!", "Middle initial field blank!")
        elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"):
            showerror("Error!", "Incorect Customer type!")
        elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()):
            showerror("Error!", "Bad entry for date, use format mm/dd/yyyy")
        else:
            self.close = True
            
            # do work
            old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(),
                                           str(self.mname.get()).strip())
            new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(),
                   str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")]
            
            if not old and self.close:
                self.new_customer_name = ' '.join([new[1],new[2],new[0]])
                self.customers.add(new)
            elif self.close and not self.edit:
                var = IntVar()
                
                diag = AlreadyExistsDialog(self.root, new, old, var)
                diag.show()
                if var.get() == 0: # edit
                    self.close = False
                if var.get() == 1: # replace
                    self.customers.replace(row, new)
                    self.new_customer_name = ' '.join([new[1],new[2],new[0]])
                elif var.get() == 2: # add duplicate
                    self.customers.add(new)
                    self.new_customer_name = ' '.join([new[1],new[2],new[0]])
            else:
                self.customers.replace(row, new)

            if self.close:
                self.refresh()
                self.root.quit()
Beispiel #11
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)
                
                #VARIABLES GLOBALES
                global cedula, titulo, residencia, nombres, apellidos, direccion, telefono, envio, correo, celular, dia, mes, profesion, empresa, oficina, tel, telfax, banco, tcuenta, numcuenta, tipopersona, retefuente, reteiva, gcontribuyente, gfactura, gcheque, notas, co1cc, co1nombres, co1dir, co1tel1, co1cargo, co1empresa, co1oficina, co1tel2, co2cc, co2nombres, co2dir, co2tel1, co2cargo, co2empresa, co2oficina, co2tel2, co3cc, co3nombres, co3dir, co3tel1, co3cargo, co3empresa, co3oficina, co3tel2, lb, note, busqueda, dato, E
                
                #INSTANCIEAS DE LOS WIDGETS
                global codeE, refE, cityE, nameE, lastnameE, adressE, phoneE, mailE, emailE, mobileE, birthdayE, birthdayCbx, ocupationE, companyE, ofiE, officetelE, faxE, bankCbx, banktypeCbx, numbankE, personR1, personR2, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc1E, name1E, adress1E, phone1E, job1E, jobphone1E, office1E, officetel1E, cc2E, name2E, adress2E, phone2E, job2E, jobphone2E, office2E, officetel2E, cc3E, name3E, adress3E, phone3E, job3E, jobphone3E, office3E, officetel3E, add, update, delete, clean, cancel
                global info, _arrendatarios

                _arrendatarios = dict()
                
                #Variables
                cedula = StringVar()
                titulo = StringVar()
                residencia = StringVar()
                nombres = StringVar()
                apellidos = StringVar()
                direccion = StringVar()
                telefono = StringVar()
                envio = StringVar()
                correo = StringVar()
                celular = StringVar()
                dia = IntVar()
                mes = StringVar()
                meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"]
                profesion = StringVar()
                empresa = StringVar()
                oficina = StringVar()
                tel = StringVar()
                telfax = StringVar()
                banco = StringVar()
                bancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"]
                banktype = ['Corriente','Ahorro']
                tcuenta = StringVar()
                numcuenta = StringVar()
                tipopersona = IntVar()  
                retefuente = IntVar()
                reteiva = IntVar()
                gcontribuyente = IntVar()
                gfactura = IntVar()
                gcheque = IntVar()
                notas = StringVar()
                
                #----------------------------
                
                co1cc = StringVar()
                co1nombres = StringVar()
                co1dir = StringVar()
                co1tel1 = StringVar()
                co1cargo = StringVar()
                co1empresa = StringVar()
                co1oficina = StringVar()
                co1tel2 = StringVar()
                
                co2cc = StringVar()
                co2nombres = StringVar()
                co2dir = StringVar()
                co2tel1 = StringVar()
                co2cargo = StringVar()
                co2empresa = StringVar()
                co2oficina = StringVar()
                co2tel2 = StringVar()
                
                co3cc = StringVar()
                co3nombres = StringVar()
                co3dir = StringVar()
                co3tel1 = StringVar()
                co3cargo = StringVar()
                co3empresa = StringVar()
                co3oficina = StringVar()
                co3tel2 = StringVar()
                
                #BUSQUEDA = ["Nombre","CC/Nit"]
                busqueda = StringVar()
                busqueda.trace("w", lambda name, index, mode: buscar())
                info = IntVar()
                dato = StringVar()

                #WIDGETS
                
                #========================= HEADER ===========================
                
                self.header = Label(self, text="GESTIÓN DE ARRENDATARIOS", font="bold")
                self.header.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)
                
                #================ NOTEBOOK =============>
                
                self.nb = Notebook(self.wrapper)
                
                #-----------------------> TAB 1
                
                self.tab1 = Frame (self.nb)
                
                self.f0 = Frame(self.tab1)#Para dejar espacio entre Tab y Label
                self.f0.pack(fill=X, pady=10)#-------------------------------

                #======================= DATOS GENERALES =======================
                
                self.f0 = Frame(self.tab1)
                self.f0.pack(pady=5,fill=X)#------------------------------------
                
                self.codeL = Label(self.f0, text='CC:')
                self.codeL.pack(side=LEFT)
                codeE = Entry(self.f0, textvariable=cedula, width=10)
                codeE.pack(side=LEFT, fill=X, expand=1)
                codeE.focus_set()

                self.refL = Label(self.f0, text='Título:')
                self.refL.pack(side=LEFT)
                refE = Entry(self.f0, textvariable=titulo, width=10)
                refE.pack(side=LEFT)
                #refE.bind("<KeyRelease>", caps)

                self.cityL = Label(self.f0, text='Ciudad de residencia:')
                self.cityL.pack(side=LEFT)
                cityE = Entry(self.f0, textvariable=residencia, width=10)
                cityE.pack(side=LEFT)
                cityE.bind("<KeyRelease>", caps)

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

                self.nameL = Label(self.f1, text='Nombres:')
                self.nameL.pack(side=LEFT)
                nameE = Entry(self.f1, textvariable=nombres)
                nameE.pack(side=LEFT, fill=X, expand=1)
                nameE.bind("<KeyRelease>", caps)

                self.lastnameL = Label(self.f1, text='Apellidos:')
                self.lastnameL.pack(side=LEFT)
                lastnameE = Entry(self.f1, textvariable=apellidos)
                lastnameE.pack(side=LEFT, fill=X, expand=1)
                lastnameE.bind("<KeyRelease>", caps)

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

                self.adressL = Label(self.f2, text='Dir. Casa:')
                self.adressL.pack(side=LEFT)
                adressE = Entry(self.f2, textvariable=direccion)
                adressE.pack(side=LEFT, fill=X, expand=1)
                adressE.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f2, text='Teléfono:')
                self.phoneL.pack(side=LEFT)
                phoneE = Entry(self.f2, textvariable=telefono, width=20)
                phoneE.pack(side=LEFT)

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

                self.mailL = Label(self.f3, text='Dir. Correspondencia:')
                self.mailL.pack(side=LEFT)
                mailE = Entry(self.f3, textvariable=envio)
                mailE.pack(side=LEFT, fill=X, expand=1)
                mailE.bind("<KeyRelease>", caps)

                self.emailL = Label(self.f3, text='Email:')
                self.emailL.pack(side=LEFT)
                emailE = Entry(self.f3, textvariable=correo, width=15)
                emailE.pack(side=LEFT, fill=X, expand=1)

                self.f4 = Frame(self.tab1)
                self.f4.pack(pady=5,fill=X)#---------------------------
                
                self.mobileL = Label(self.f4, text='Celular:')
                self.mobileL.pack(side=LEFT)
                mobileE = Entry(self.f4, textvariable=celular, width=10)
                mobileE.pack(side=LEFT, fill=X, expand=1)

                self.birthdayL = Label(self.f4, text='Cumpleaños:')
                self.birthdayL.pack(side=LEFT)

                self.birthdayL2 = Label(self.f4, text='Día:')
                self.birthdayL2.pack(padx=5,side=LEFT)

                birthdayE = Entry(self.f4, textvariable=dia, width=3)
                birthdayE.pack(side=LEFT)
                
                #s = Spinbox(self.f4, from_=1, to=31,textvariable=dia, width=3)
                #s.pack(side=LEFT)

                self.birthdayL3 = Label(self.f4, text='Mes:')
                self.birthdayL3.pack(padx=5,side=LEFT)

                birthdayCbx = Combobox(self.f4, textvariable=mes, values=meses, width=10)
                birthdayCbx.set('Enero')
                birthdayCbx.pack(side=LEFT)

                self.lf = LabelFrame(self.tab1, text="Info laboral")#========

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

                self.ocupationL = Label(self.f5, text='Profesión:')
                self.ocupationL.pack(side=LEFT)
                ocupationE = Entry(self.f5, textvariable=profesion, width=20)
                ocupationE.pack(side=LEFT, fill=X, expand=1)
                ocupationE.bind("<KeyRelease>", caps)

                self.companyL = Label(self.f5, text='Empresa:')
                self.companyL.pack(side=LEFT)
                companyE = Entry(self.f5, textvariable=empresa, width=24)
                companyE.pack(side=LEFT, fill=X, expand=1)
                companyE.bind("<KeyRelease>", caps)

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

                self.ofiL = Label(self.f6, text='Dir. Oficina:')
                self.ofiL.pack(side=LEFT)
                ofiE = Entry(self.f6, textvariable=oficina)
                ofiE.pack(side=LEFT, fill=X, expand=1)
                ofiE.bind("<KeyRelease>", caps)

                self.officetelL = Label(self.f6, text='Tel:')
                self.officetelL.pack(side=LEFT)
                officetelE = Entry(self.f6, textvariable=tel, width=10)
                officetelE.pack(fill=X, side=LEFT)

                self.faxL = Label(self.f6, text='Fax:')
                self.faxL.pack(side=LEFT)
                faxE = Entry(self.f6, textvariable=telfax, width=10)
                faxE.pack(side=LEFT)
                
                self.lf.pack(fill=X)#===========================================
        
                self.f7 = Frame(self.tab1)
                self.f7.pack(pady=5,fill=X)#-----------------

                self.bankL = Label(self.f7, text='Banco:')
                self.bankL.pack(side=LEFT)

                bankCbx = Combobox(self.f7, textvariable=banco, values=bancos, width=12)
                bankCbx.set('')
                bankCbx.pack(side=LEFT)

                self.bankL = Label(self.f7, text='Tipo Cuenta:')
                self.bankL.pack(side=LEFT)

                banktypeCbx = Combobox(self.f7, textvariable=tcuenta, values=banktype, width=10)
                banktypeCbx.set('')
                banktypeCbx.pack(side=LEFT)

                self.numbankL = Label(self.f7, text="# Cuenta:")
                self.numbankL.pack(side=LEFT)
                numbankE = Entry(self.f7, textvariable=numcuenta, width=13)
                numbankE.pack(side=LEFT, fill=X, expand=1)

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

                self.personL = Label(self.f8, text='Tipo Persona:')
                self.personL.pack(side=LEFT)
                personR1 = Radiobutton(self.f8, text="Natural", variable=tipopersona, value=1)
                personR1.pack(padx=20,side=LEFT)
                personR2 = Radiobutton (self.f8, text="Jurídica", variable=tipopersona, value=2)
                personR2.pack(padx=20,side=LEFT)
                
                self.f = Frame(self.tab1)
                self.f.pack(pady=5,fill=X)#------------------------------------

                Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente)
                Ch1.pack(side=LEFT)
                
                Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva)
                Ch2.pack(side=LEFT)
                
                Ch3 = Checkbutton(self.f, text="Gran Contribuyente", variable=gcontribuyente)
                Ch3.pack(side=LEFT)
                
                Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura)
                Ch4.pack(side=LEFT)
                
                Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque)
                Ch5.pack(side=LEFT)

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

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

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

                note = Text(self.f10, height=5)
                note.pack(fill=X, side=LEFT)
                #note.bind("<KeyRelease>", caps)
                
                #-----------------------> TAB 2
                
                self.tab2 = Frame (self.nb)
                self.tab2.pack()
                
                self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label
                self.f0.pack(fill=X, pady=10)#----------------------------------
                
                #===================== INFORMACIÓN CODEUDOR ====================
                
                self.lf1 = LabelFrame(self.tab2, text="Codeudor 1")
                
                self.f0 = Frame(self.lf1)
                self.f0.pack(fill=X, pady=5)#-------------------------------
                
                self.ccL = Label(self.f0, text='CC:')
                self.ccL.pack(side=LEFT)
                cc1E = Entry(self.f0, textvariable= co1cc, width=10)
                cc1E.pack(side=LEFT, fill=X, expand=1)
                
                self.nameL = Label(self.f0, text='Nombres:')
                self.nameL.pack(side=LEFT)
                name1E = Entry(self.f0, textvariable=co1nombres)
                name1E.pack(side=LEFT, fill=X, expand=1)
                name1E.bind("<KeyRelease>", caps)
                
                self.f1 = Frame(self.lf1)
                self.f1.pack(fill=X, pady=5)#-------------------------------
                
                self.adressL = Label(self.f1, text='Dir. Casa:')
                self.adressL.pack(side=LEFT)
                adress1E = Entry(self.f1, textvariable=co1dir)
                adress1E.pack(side=LEFT, fill=X, expand=1)
                adress1E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f1, text='Tel:')
                self.phoneL.pack(side=LEFT)
                phone1E = Entry(self.f1, textvariable=co1tel1, width=20)
                phone1E.pack(side=LEFT)
                
                self.f2 = Frame(self.lf1)
                self.f2.pack(fill=X, pady=5)#-------------------------------
                
                self.jobL = Label(self.f2, text='Cargo:')
                self.jobL.pack(side=LEFT)
                job1E = Entry(self.f2, textvariable=co1cargo, width=20)
                job1E.pack(side=LEFT, fill=X, expand=1)
                job1E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f2, text='Empresa:')
                self.phoneL.pack(side=LEFT)
                jobphone1E = Entry(self.f2, textvariable=co1empresa)
                jobphone1E.pack(side=LEFT)
                jobphone1E.bind("<KeyRelease>", caps)
                
                self.f3 = Frame(self.lf1)
                self.f3.pack(fill=X, pady=5)#-------------------------------
                
                self.officeL = Label(self.f3, text='Dir. Oficina:')
                self.officeL.pack(side=LEFT)
                office1E = Entry(self.f3, textvariable=co1oficina)
                office1E.pack(side=LEFT, fill=X, expand=1)
                office1E.bind("<KeyRelease>", caps)

                self.officetelL = Label(self.f3, text='Tel:')
                self.officetelL.pack(side=LEFT)
                officetel1E = Entry(self.f3, textvariable=co1tel2, width=20)
                officetel1E.pack(fill=X, side=LEFT)
                
                self.lf1.pack(fill=X, ipady=5)#=================================
                
                self.lf2 = LabelFrame(self.tab2, text="Codeudor 2")
                
                self.f0 = Frame(self.lf2)
                self.f0.pack(fill=X, pady=5)#-------------------------------
                
                self.ccL = Label(self.f0, text='CC:')
                self.ccL.pack(side=LEFT)
                cc2E = Entry(self.f0, textvariable=co2cc, width=10)
                cc2E.pack(side=LEFT, fill=X, expand=1)
                
                self.nameL = Label(self.f0, text='Nombres:')
                self.nameL.pack(side=LEFT)
                name2E = Entry(self.f0, textvariable=co2nombres)
                name2E.pack(side=LEFT, fill=X, expand=1)
                name2E.bind("<KeyRelease>", caps)
                
                self.f1 = Frame(self.lf2)
                self.f1.pack(fill=X, pady=5)#-------------------------------
                
                self.adressL = Label(self.f1, text='Dir. Casa:')
                self.adressL.pack(side=LEFT)
                adress2E = Entry(self.f1, textvariable=co2dir)
                adress2E.pack(side=LEFT, fill=X, expand=1)
                adress2E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f1, text='Tel:')
                self.phoneL.pack(side=LEFT)
                phone2E = Entry(self.f1, textvariable=co2tel1, width=20)
                phone2E.pack(side=LEFT)
                
                self.f2 = Frame(self.lf2)
                self.f2.pack(fill=X, pady=5)#-------------------------------
                
                self.adressL = Label(self.f2, text='Cargo:')
                self.adressL.pack(side=LEFT)
                job2E = Entry(self.f2, textvariable=co2cargo, width=20)
                job2E.pack(side=LEFT, fill=X, expand=1)
                job2E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f2, text='Empresa:')
                self.phoneL.pack(side=LEFT)
                jobphone2E = Entry(self.f2, textvariable=co2empresa)
                jobphone2E.pack(side=LEFT)
                jobphone2E.bind("<KeyRelease>", caps)
                
                self.f3 = Frame(self.lf2)
                self.f3.pack(fill=X, pady=5)#-------------------------------
                
                self.officeL = Label(self.f3, text='Dir. Oficina:')
                self.officeL.pack(side=LEFT)
                office2E = Entry(self.f3, textvariable=co2oficina)
                office2E.pack(side=LEFT, fill=X, expand=1)
                office2E.bind("<KeyRelease>", caps)

                self.officetelL = Label(self.f3, text='Tel:')
                self.officetelL.pack(side=LEFT)
                officetel2E = Entry(self.f3, textvariable=co2tel2, width=20)
                officetel2E.pack(fill=X, side=LEFT)
                
                self.lf2.pack(fill=X, ipady=5)#=================================
                
                self.lf3 = LabelFrame(self.tab2, text="Codeudor 3")
                
                self.f0 = Frame(self.lf3)
                self.f0.pack(fill=X, pady=5)#-------------------------------
                
                self.ccL = Label(self.f0, text='CC:')
                self.ccL.pack(side=LEFT)
                cc3E = Entry(self.f0, textvariable=co3cc, width=10)
                cc3E.pack(side=LEFT, fill=X, expand=1)
                
                self.nameL = Label(self.f0, text='Nombres:')
                self.nameL.pack(side=LEFT)
                name3E = Entry(self.f0, textvariable=co3nombres)
                name3E.pack(side=LEFT, fill=X, expand=1)
                name3E.bind("<KeyRelease>", caps)
                
                self.f1 = Frame(self.lf3)
                self.f1.pack(fill=X, pady=5)#-------------------------------
                
                self.adressL = Label(self.f1, text='Dir. Casa:')
                self.adressL.pack(side=LEFT)
                adress3E = Entry(self.f1, textvariable=co3dir)
                adress3E.pack(side=LEFT, fill=X, expand=1)
                adress3E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f1, text='Tel:')
                self.phoneL.pack(side=LEFT)
                phone3E = Entry(self.f1, textvariable=co3tel1, width=20)
                phone3E.pack(side=LEFT)
                
                self.f2 = Frame(self.lf3)
                self.f2.pack(fill=X, pady=5)#-------------------------------
                
                self.adressL = Label(self.f2, text='Cargo:')
                self.adressL.pack(side=LEFT)
                job3E = Entry(self.f2, textvariable=co3cargo, width=20)
                job3E.pack(side=LEFT, fill=X, expand=1)
                job3E.bind("<KeyRelease>", caps)

                self.phoneL = Label(self.f2, text='Empresa:')
                self.phoneL.pack(side=LEFT)
                jobphone3E = Entry(self.f2, textvariable=co3empresa)
                jobphone3E.pack(side=LEFT)
                jobphone3E.bind("<KeyRelease>", caps)
                
                self.f3 = Frame(self.lf3)
                self.f3.pack(fill=X, pady=5)#-------------------------------
                
                self.officeL = Label(self.f3, text='Dir. Oficina:')
                self.officeL.pack(side=LEFT)
                office3E = Entry(self.f3, textvariable=co3oficina)
                office3E.pack(side=LEFT, fill=X, expand=1)
                office3E.bind("<KeyRelease>", caps)

                self.officetelL = Label(self.f3, text='Tel:')
                self.officetelL.pack(side=LEFT)
                officetel3E = Entry(self.f3, textvariable=co3tel2, width=20)
                officetel3E.pack(fill=X, side=LEFT)
                
                self.lf3.pack(fill=X, ipady=5)#=================================
                
                #---------------------------------------------------------------
                
                self.nb.add (self.tab1, text="Datos Generales")
                self.nb.add(self.tab2, text="Información Codeudor")
                
                self.nb.pack()

                #=========================== BOTONES ===========================
                
                self.fBtn = Frame(self.wrapper)
                self.fBtn.pack()#-------------------------------
        
                clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
                clean.pack(side=RIGHT)
                
                update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED)
                update.pack(side=RIGHT)
                
                add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
                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 ARRENDATARIOS")
                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, bg='#d8ecf3')
                scroll.config (command=lb.yview)
                lb.pack(fill=BOTH)
                lb.bind("<Double-Button-1>", callback)
                
                self.wrap2 = Frame(self.aside)
                self.wrap2.pack()
                
                load = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista)
                load.pack(fill=X)
                
                delete = Button(self.wrap2, text='Borrar', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
                delete.pack(fill=X)
                
                edit = Button(self.wrap2, text='Modificar', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar)
                edit.pack(fill=X)
                
                self.wrap3 = Frame(self.aside)
                self.wrap3.pack()
                
                buscador = Label(self.wrap3, text="Buscar por:")
                buscador.pack(side=LEFT)
                
                R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1)
                R1.pack(side=LEFT)
                R2 = Radiobutton (self.wrap3, text="Apellido", variable=info, value=2)
                R2.pack(side=LEFT)
                info.set(1)
                
                self.wrap4 = Frame(self.aside)
                self.wrap4.pack()
                
                E = Entry(self.wrap4, textvariable=busqueda, width=24)
                E.pack()
                E.bind("<KeyRelease>", caps)
                
                """
Beispiel #12
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        global cedula, codigo, ref, nombre, direccion, ciudad, telefono, gcontribuyente, gcheque, titular, banco, tipocuenta, numcuenta, notas, busqueda
        global ccE, codE, tituloE, nameE, locacionE, cityE, niE, ch1, ch2, tnameE, bankCbx, tbankCbx, tcuentaE, note, lb, add, clean, delete, update
        global info

        #VARIABLES
        cedula = StringVar()
        codigo = IntVar()
        ref = StringVar()
        nombre = StringVar()
        direccion = StringVar()
        ciudad = StringVar()
        telefono = StringVar()
        gcontribuyente = IntVar()
        gcheque = IntVar()
        titular = StringVar()
        banco = StringVar()
        tipocuenta = StringVar()
        numcuenta = StringVar()
        notas = StringVar()

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

        tbanktype = ['Corriente', 'Ahorro']

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

        #WIDGETS

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

        self.titleL = Label(self, text="GESTIÓN DE TERCEROS", 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)

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

        self.niL = Label(self.f1, text='CC/Nit:')
        self.niL.pack(side=LEFT)
        ccE = Entry(self.f1, textvariable=cedula)
        ccE.pack(side=LEFT)
        ccE.focus_set()

        l3 = Label(self.f1, text='Codigo:')
        l3.pack(side=LEFT)
        codE = Entry(self.f1, textvariable=codigo)
        codE.pack(side=LEFT)
        codE.bind("<KeyRelease>", caps)

        self.tituloL = Label(self.f1, text='Título:')
        self.tituloL.pack(side=LEFT)
        tituloE = Entry(self.f1, textvariable=ref)
        tituloE.pack(side=LEFT)
        #tituloE.bind("<KeyRelease>", caps)

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

        self.nameL = Label(self.f2, text='Nombre:')
        self.nameL.pack(side=LEFT)
        nameE = Entry(self.f2, textvariable=nombre)
        nameE.pack(side=LEFT, fill=X, expand=1)
        nameE.bind("<KeyRelease>", caps)

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

        self.locacionL = Label(self.f3, text='Dirección:')
        self.locacionL.pack(side=LEFT)
        locacionE = Entry(self.f3, textvariable=direccion)
        locacionE.pack(side=LEFT, fill=X, expand=1)
        locacionE.bind("<KeyRelease>", caps)

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

        self.cityL = Label(self.f4, text='Ciudad de residencia:')
        self.cityL.pack(side=LEFT)
        cityE = Entry(self.f4, textvariable=ciudad)
        cityE.pack(side=LEFT, fill=X, expand=1)
        cityE.bind("<KeyRelease>", caps)

        self.niL = Label(self.f4, text='Teléfono:')
        self.niL.pack(side=LEFT)
        niE = Entry(self.f4, textvariable=telefono)
        niE.pack(side=LEFT, fill=X, expand=1)

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

        ch1 = Checkbutton(self.f5,
                          text="Gran Contribuyente",
                          variable=gcontribuyente,
                          state=DISABLED)
        ch1.pack(side=RIGHT)

        ch2 = Checkbutton(self.f5,
                          text="Genera Cheque",
                          variable=gcheque,
                          state=DISABLED)
        ch2.pack(side=RIGHT)

        self.lf = LabelFrame(self.wrapper, text="Datos Titular")  #=======

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

        self.tnameL = Label(self.f6, text='Nombres:')
        self.tnameL.pack(side=LEFT)
        tnameE = Entry(self.f6, textvariable=titular)
        tnameE.pack(side=LEFT, fill=X, expand=1)
        tnameE.bind("<KeyRelease>", caps)

        self.f7 = Frame(self.lf)
        self.f7.pack(
            fill=X)  #-------------------------------------------------

        self.tbancpL = Label(self.f7, text='Banco:')
        self.tbancpL.pack(side=LEFT)
        bankCbx = Combobox(self.f7,
                           textvariable=banco,
                           values=tbancos,
                           width=12)
        bankCbx.set('')
        bankCbx.pack(side=LEFT)

        self.tbancpL = Label(self.f7, text='Tipo Cuenta:')
        self.tbancpL.pack(side=LEFT)
        tbankCbx = Combobox(self.f7,
                            textvariable=tipocuenta,
                            values=tbanktype,
                            width=8)
        tbankCbx.set('')
        tbankCbx.pack(side=LEFT)

        self.tcuentaL = Label(self.f7, text='# Cuenta:')
        self.tcuentaL.pack(side=LEFT)
        tcuentaE = Entry(self.f7, textvariable=numcuenta)
        tcuentaE.pack(side=LEFT, fill=X, expand=1)

        self.lf.pack(fill=X, ipady=5)  #================================

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

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

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

        note = Text(self.f10, height=5)
        note.pack(fill=X, side=LEFT)

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

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

        update = Button(self.fBtn,
                        text='Actualizar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=None,
                        state=DISABLED)
        update.pack(side=RIGHT)

        add = Button(self.fBtn,
                     text='Agregar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=Agregar)
        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 TERCEROS")
        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,
                     bg='#d8ecf3')
        scroll.config(command=lb.yview)
        lb.pack(fill=BOTH)
        lb.bind("<Double-Button-1>", callback)

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

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

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

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

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

        buscador = Label(self.wrap3, text="Buscar por:")
        buscador.pack(side=LEFT)

        R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1)
        R1.pack(side=LEFT)
        R2 = Radiobutton(self.wrap3, text="Nombre", variable=info, value=2)
        R2.pack(side=LEFT)
        info.set(1)

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

        E = Entry(self.wrap4, textvariable=busqueda, width=24)
        E.pack()
        E.bind("<KeyRelease>", caps)
Beispiel #13
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        #VARIABLES GLOBALES
        global codigo, direccion, piso, telefono, ciudad, zona, barrio, estrato, llaves, preguntarx, fin, vlrenta, vladmon, incluida, vlventa, vlavaluo, comiventa, pagoprop, fpagoprop, fpagoadmin, tpropiedad, area, lineas, habitaciones, closets, lamparas, duchas, lavamanos, tsala, tcocina, tpiso, tgarage, rutabus, aservicio, ascensor, citofono, aguacaliente, biblioteca, zverdes, terraza, trifilar, parqueadero, observaciones, lb, Cbx1, Cbx2, zona1, zona2, zona3, zona4, zona5, busqueda, dato, E
        #INSTANCIAS DE LOS WIDGETS
        global codE, adressE, comisionE, phoneE, cityCbx, Cbx1, Cbx2, estratoE, keysE, askforE, rent, arriendoE, admonE, include, sale, ventaE, avaluadoE, comiE, pagopropietarioE, diapagopropietarioE, diapagoadmonE, propertyCbx, areaE, lineasE, roomE, closetE, lampE, bathE, sinkE, salasCbx, cocinaCbx, pisoCbx, garageCbx, rutaE, chkb0, chkb1, chkb2, chkb3, chkb4, chkb5, chkb6, chkb7, chkb8, observaciones, add, delete, edit, clean, update

        #Variables
        codigo = IntVar()
        direccion = StringVar()
        piso = IntVar()
        telefono = StringVar()
        ciudad = StringVar()
        zona = StringVar()
        barrio = StringVar()
        estrato = StringVar()
        llaves = StringVar()
        preguntarx = StringVar()
        fin = IntVar()
        vlrenta = IntVar()
        vladmon = IntVar()
        incluida = IntVar()
        vlventa = IntVar()
        vlavaluo = IntVar()
        comiventa = DoubleVar()
        pagoprop = IntVar()
        fpagoprop = IntVar()
        fpagoadmin = IntVar()

        tpropiedad = StringVar()
        area = IntVar()
        lineas = IntVar()
        habitaciones = IntVar()
        closets = IntVar()
        lamparas = IntVar()
        duchas = IntVar()
        lavamanos = IntVar()
        tsala = StringVar()
        tcocina = StringVar()
        tpiso = StringVar()
        tgarage = StringVar()
        rutabus = StringVar()

        aservicio = IntVar()
        ascensor = IntVar()
        citofono = IntVar()
        aguacaliente = IntVar()
        biblioteca = IntVar()
        zverdes = IntVar()
        terraza = IntVar()
        trifilar = IntVar()
        parqueadero = IntVar()

        ciudades = [
            'Medellín', 'Envigado', 'Caldas', 'El Retiro', 'Guatapé',
            'Bogotá D.C', 'Bello', 'Copacabana', 'Rionegro', 'Sabaneta',
            "Girardot", "Itaguí"
        ]
        zonas = ["Zona 1", "Zona 2", "Zona 3", "Zona 4", "Zona 5"]
        zona1 = [
            'Centro', 'Manrique', 'Aranjuez', 'Prado', 'Buenos Aires',
            'Loreto', 'Milagrosa', 'Villa Hermosa', 'Boston', 'Campo Valdés'
        ]
        zona2 = [
            'Poblado', 'Patio  Bonito', 'Provenza', 'Castropol', 'Manila',
            'San Lucas', 'Envigado', 'El Dorado', 'Loma de Escobero',
            'Sabaneta', 'San Diego', 'Las Palmas', 'La Sebastiana'
        ]
        zona3 = [
            'Laureles', 'La América', 'Estadio', 'Santa Mónica', 'Floresta',
            'Conquistadores', 'Florida Nueva', 'Robledo', 'Los Colores',
            'San Joaquín', 'Castilla', 'Pedregal', 'Tricentenario', 'Bello',
            'Florencia', 'Boyacá las Brisas', 'Barrio Nuevo', 'La Mota',
            'Calazans', 'Simón Bolivar', 'El Portal', 'Envigado'
        ]
        zona4 = [
            'Rosales', 'Guayabal', 'Belén', 'Itaguí', 'La Estrella',
            'Manzanares', 'El Carmelo', 'Mayorca'
        ]
        zona5 = ['El Retiro']

        negociacion = StringVar()
        propiedades = [
            'Casa', 'Apartamento', 'Local', 'Local comercial',
            'Local industrial', 'Oficina', 'Bodega', 'Finca', 'Casa finca',
            'Cabaña', 'Apartaestudio', 'Apartalock', 'Lote', 'Consultorio',
            'Parqueadero'
        ]
        comodidades = [
            "ALCOBA DE SERVICIO", "ASCENDOR", "CITÓFONO", "AGUA CALIENTE",
            "BIBLIOTECA", "ZONAS VERDES", "PARQUEADERO VISITANES", "TRIFILAR",
            "TERRAZA"
        ]
        salas = ['Salón', 'Salón comedor', 'Sala garage']
        cocina = [
            'Integral', 'Semintegral', 'Sencilla', 'Mixta', 'Cocineta',
            'Integral a gas'
        ]
        pisos = [
            'Baldosa', 'Mármol', 'Cerámica', 'Alfombra', 'Mármol y Cerámica',
            'Alfombra y Cerámica', 'Reforzado', 'Porcelanato', 'Madera'
        ]
        garage = ['Cubierto', 'Eléctrico', 'Descubierto', 'Paralelo']

        #busqueda = ["Código","Dirección"]
        busqueda = StringVar()
        busqueda.trace("w", lambda name, index, mode: buscar())
        dato = IntVar()

        #WIDGETS

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

        self.header = Label(self, text="GESTIÓN DE IMNUEBLES", font="bold")
        self.header.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)

        #================ NOTEBOOK =============>

        self.nb = Notebook(self.wrapper)

        #-----------------------> TAB 1

        self.tab1 = Frame(self.nb)

        self.f0 = Frame(
            self.tab1)  #Es para dejar un espacio entre el Tab y el Label
        self.f0.pack(fill=X, pady=10)  #-------------------------------

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

        self.codL = Label(self.f1, text='Código:')
        self.codL.pack(side=LEFT)
        codE = Entry(self.f1, textvariable=codigo, width=5)
        codE.pack(side=LEFT)
        codE.focus_set()

        self.adressL = Label(self.f1, text='Dir. Casa:')
        self.adressL.pack(side=LEFT)
        adressE = Entry(self.f1, textvariable=direccion)
        adressE.pack(side=LEFT, fill=X, expand=1)
        adressE.bind("<KeyRelease>", caps)

        self.comisionL = Label(self.f1, text='Piso:')
        self.comisionL.pack(side=LEFT)
        comisionE = Entry(self.f1, textvariable=piso, width=5)
        comisionE.pack(side=LEFT)

        self.phoneL = Label(self.f1, text='Tel:')
        self.phoneL.pack(side=LEFT)
        phoneE = Entry(self.f1, textvariable=telefono, width=20)
        phoneE.pack(side=LEFT)

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

        self.cityL = Label(self.f2, text='Ciudad:')
        self.cityL.pack(side=LEFT)

        cityCbx = Combobox(self.f2,
                           textvariable=ciudad,
                           values=ciudades,
                           width=10)
        cityCbx.set('')
        cityCbx.pack(side=LEFT, fill=X, expand=1)

        self.zoneL = Label(self.f2, text='Zona:')
        self.zoneL.pack(side=LEFT)

        Cbx1 = Combobox(self.f2, textvariable=zona, values=zonas, width=10)
        Cbx1.set('')
        Cbx1.bind("<<ComboboxSelected>>", zone)
        Cbx1.pack(side=LEFT, fill=X, expand=1)

        self.neighborL = Label(self.f2, text='Barrio:')
        self.neighborL.pack(side=LEFT)

        Cbx2 = Combobox(self.f2, textvariable=barrio, width=10)
        Cbx2.set('')
        Cbx2.pack(side=LEFT, fill=X, expand=1)

        self.estratoL = Label(self.f2, text='Estrato:')
        self.estratoL.pack(side=LEFT)
        estratoE = Entry(self.f2, textvariable=estrato, width=5)
        estratoE.pack(side=LEFT)

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

        self.keysL = Label(self.f3, text='Llaves en:')
        self.keysL.pack(side=LEFT)
        keysE = Entry(self.f3, textvariable=llaves, width=24)
        keysE.pack(side=LEFT, fill=X, expand=1)
        keysE.bind("<KeyRelease>", caps)

        self.askforL = Label(self.f3, text='Preguntar por:')
        self.askforL.pack(side=LEFT)
        askforE = Entry(self.f3, textvariable=preguntarx, width=24)
        askforE.pack(side=LEFT, fill=X, expand=1)
        askforE.bind("<KeyRelease>", caps)

        self.negociacionLF = LabelFrame(self.tab1, text="Valores Negociación")
        self.negociacionLF.pack(anchor=W, pady=5,
                                fill=X)  #----------------------

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

        rent = Radiobutton(self.f5a,
                           text="Se Arrienda: ",
                           variable=fin,
                           value=1)

        rent.pack(side=LEFT)

        self.arriendoL = Label(self.f5a, text='Valor $')
        self.arriendoL.pack(side=LEFT)
        arriendoE = Entry(self.f5a, textvariable=vlrenta, width=15)
        arriendoE.pack(side=LEFT)

        self.admonL = Label(self.f5a, text='Administración $')
        self.admonL.pack(side=LEFT)
        admonE = Entry(self.f5a, textvariable=vladmon, width=15)
        admonE.pack(side=LEFT)

        include = Checkbutton(self.f5a,
                              text="Admin. incluida",
                              variable=incluida)
        include.pack(side=LEFT)

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

        sale = Radiobutton(self.f5b, text="Se Vende: ", variable=fin, value=2)

        sale.pack(side=LEFT)

        self.ventaL = Label(self.f5b, text='Valor $')
        self.ventaL.pack(side=LEFT)
        ventaE = Entry(self.f5b, textvariable=vlventa, width=15)
        ventaE.pack(side=LEFT)

        self.avaluadoL = Label(self.f5b, text='Avaluado $')
        self.avaluadoL.pack(side=LEFT)
        avaluadoE = Entry(self.f5b, textvariable=vlavaluo, width=15)
        avaluadoE.pack(side=LEFT)

        self.comiL = Label(self.f5b, text='Comisión Venta')
        self.comiL.pack(side=LEFT)
        comiE = Entry(self.f5b, textvariable=comiventa, width=5)
        comiE.pack(side=LEFT)
        self.porcentL = Label(self.f5b, text='%')
        self.porcentL.pack(side=LEFT)

        self.pagoLF = LabelFrame(self.tab1, text="Detalles de pago")
        self.pagoLF.pack(anchor=W, pady=5, fill=X)  #-----------

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

        self.pagopropietarioL = Label(self.f6, text='$ Pago Propietario:')
        self.pagopropietarioL.pack(side=LEFT)
        pagopropietarioE = Entry(self.f6, textvariable=pagoprop, width=10)
        pagopropietarioE.pack(side=LEFT, fill=X, expand=1)

        self.diapagopropietarioL = Label(self.f6, text='Día Pago Propietario:')
        self.diapagopropietarioL.pack(side=LEFT)
        diapagopropietarioE = Entry(self.f6, textvariable=fpagoprop, width=5)
        diapagopropietarioE.pack(side=LEFT)

        self.diapagoadmonL = Label(self.f6, text='Día Pago Admon:')
        self.diapagoadmonL.pack(side=LEFT)
        diapagoadmonE = Entry(self.f6, textvariable=fpagoadmin, width=5)
        diapagoadmonE.pack(side=LEFT)

        self.tab1.pack()

        #-----------------------> TAB 2

        self.tab2 = Frame(self.nb)
        self.tab2.pack()

        self.f0 = Frame(self.tab2)
        self.f0.pack(fill=X, pady=10)  #-------------------------------

        self.f1 = Frame(self.tab2)
        self.f1.pack(fill=X)  #-------------------------------

        self.propertyL = Label(self.f1, text='Tipo Propiedad:')
        self.propertyL.pack(side=LEFT)

        propertyCbx = Combobox(self.f1,
                               textvariable=tpropiedad,
                               values=propiedades,
                               width=15)
        propertyCbx.set('')
        propertyCbx.pack(side=LEFT)

        self.areaL = Label(self.f1, text='Área:')
        self.areaL.pack(side=LEFT)
        areaE = Entry(self.f1, textvariable=area, width=5)
        areaE.pack(side=LEFT)
        self.m2L = Label(self.f1, text='m2')
        self.m2L.pack(side=LEFT)

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

        self.lineasL = Label(self.f1, text='# Líneas:')
        self.lineasL.pack(side=LEFT)
        lineasE = Entry(self.f1, textvariable=lineas, width=5)
        lineasE.pack(side=LEFT)

        self.roomL = Label(self.f1, text='# Habitaciones:')
        self.roomL.pack(side=LEFT)
        roomE = Entry(self.f1, textvariable=habitaciones, width=5)
        roomE.pack(side=LEFT)

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

        self.closetL = Label(self.f2, text='# Closets:')
        self.closetL.pack(side=LEFT)
        closetE = Entry(self.f2, textvariable=closets, width=5)
        closetE.pack(side=LEFT)

        self.lampL = Label(self.f2, text='# Lámparas:')
        self.lampL.pack(side=LEFT)
        lampE = Entry(self.f2, textvariable=lamparas, width=5)
        lampE.pack(side=LEFT)

        self.bathL = Label(self.f2, text='# Baños:')
        self.bathL.pack(side=LEFT)
        bathE = Entry(self.f2, textvariable=duchas, width=5)
        bathE.pack(side=LEFT)

        self.sinkL = Label(self.f2, text='# Lavamanos:')
        self.sinkL.pack(side=LEFT)
        sinkE = Entry(self.f2, textvariable=lavamanos, width=5)
        sinkE.pack(side=LEFT)

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

        self.salaL = Label(self.f4, text='Tipo Sala:')
        self.salaL.pack(side=LEFT)

        salasCbx = Combobox(self.f4, textvariable=tsala, values=salas)
        salasCbx.set('')
        salasCbx.pack(side=LEFT)

        self.cocinaL = Label(self.f4, text='Tipo Cocina:')
        self.cocinaL.pack(side=LEFT)

        cocinaCbx = Combobox(self.f4, textvariable=tcocina, values=cocina)
        cocinaCbx.set('')
        cocinaCbx.pack(side=LEFT)

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

        self.pisoL = Label(self.f5, text='Tipo Piso:')
        self.pisoL.pack(side=LEFT)

        pisoCbx = Combobox(self.f5, textvariable=tpiso, values=pisos)
        pisoCbx.set('')
        pisoCbx.pack(side=LEFT)

        self.garageL = Label(self.f5, text='Tipo garage:')
        self.garageL.pack(side=LEFT)

        garageCbx = Combobox(self.f5, textvariable=tgarage, values=garage)
        garageCbx.set('')
        garageCbx.pack(side=LEFT)

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

        self.rutaL = Label(self.f6, text='Ruta de Buses:')
        self.rutaL.pack(side=LEFT)
        rutaE = Entry(self.f6, textvariable=rutabus, width=30)
        rutaE.pack(side=LEFT)

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

        self.comodidades = LabelFrame(self.f7, text="Comodidades:")
        self.comodidades.pack(anchor=W, pady=5, fill=X,
                              expand=1)  #----------------------

        chkb0 = Checkbutton(self.comodidades,
                            text="ALCOBA DE SERVICIO",
                            variable=aservicio)
        chkb0.grid(row=0, column=0, sticky=W)
        chkb1 = Checkbutton(self.comodidades,
                            text="ASCENSOR",
                            variable=ascensor)
        chkb1.grid(row=0, column=1, sticky=W)
        chkb2 = Checkbutton(self.comodidades,
                            text="CITÓFONO",
                            variable=citofono)
        chkb2.grid(row=0, column=2, sticky=W)
        chkb3 = Checkbutton(self.comodidades,
                            text="AGUA CALIENTE",
                            variable=aguacaliente)
        chkb3.grid(row=0, column=3, sticky=W)

        chkb4 = Checkbutton(self.comodidades,
                            text="BIBLIOTECA",
                            variable=biblioteca)
        chkb4.grid(row=1, column=0, sticky=W)
        chkb5 = Checkbutton(self.comodidades,
                            text="ZONAS VERDES",
                            variable=zverdes)
        chkb5.grid(row=1, column=1, sticky=W)
        chkb6 = Checkbutton(self.comodidades, text="TERRAZA", variable=terraza)
        chkb6.grid(row=1, column=2, sticky=W)
        chkb7 = Checkbutton(self.comodidades,
                            text="TRIFILAR",
                            variable=trifilar)
        chkb7.grid(row=1, column=3, sticky=W)

        chkb8 = Checkbutton(self.comodidades,
                            text="PARQUEADERO VISITANTES",
                            variable=parqueadero)
        chkb8.grid(row=2, column=0, sticky=W)

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

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

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

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

        #---------------------------------------------------------------

        self.nb.add(self.tab1, text="Datos Generales")
        self.nb.add(self.tab2, text="Inventario y Comodidades")

        self.nb.pack()

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

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

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

        update = Button(self.fBtn,
                        text='Actualizar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=actualizar,
                        state=DISABLED)
        update.pack(side=RIGHT)

        add = Button(self.fBtn,
                     text='Agregar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=Agregar)
        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 INMUEBLES")
        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,
                     bg='#d8ecf3')
        scroll.config(command=lb.yview)
        lb.pack(fill=BOTH)
        lb.bind("<Double-Button-1>", callback)

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

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

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

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

        buscador = Label(self.wrap2, text="Buscar por Código:")
        buscador.pack()
        E = Entry(self.wrap2, textvariable=busqueda, width=24)
        E.pack()
        E.bind("<KeyRelease>", caps)
Beispiel #14
0
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

		global cc, nombre, inmuebles, valor, mes, meses, cbox
		
		lupa = PhotoImage(file='img/lupa.gif')
		cc = StringVar()
		nombre = StringVar()
		inmuebles = StringVar()
		valor = DoubleVar()
		
		mes = StringVar()
		meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"]
		
		#WIDGETS
		
		#=========================== HEADER ============================
		
		self.titleL = Label(self, text="REAJUSTES A PROPIETARIOS", font="bold")
		self.titleL.pack(pady=20, side=TOP)
		
		#=========================== WRAPPER ===========================
		
		self.wrapper = Frame (self)
		self.wrapper.pack(side=TOP, fill=Y)
		
		lf = LabelFrame(self.wrapper, text="Propietario / Inmueble")
		lf.pack(fill=X)
		
		f = Frame(lf)
		f.pack(pady=5, fill=X)#-----------------------------------
		
		e = Entry (f, textvariable=cc, width=20)
		e.pack(side=LEFT)
		
		b1 = Button(f, image=lupa, command=buscar)
		b1.image = lupa
		b1.pack(side=LEFT)
		
		cbox = Combobox(f, textvariable=inmuebles, width=30)
		cbox.pack(side=LEFT, fill=X, expand=1)
		
		f0 = Frame(lf)
		f0.pack(side=TOP,pady=5, fill=X)#-----------------------------------
		
		e2 = Entry (f0, textvariable=nombre, width=60, state=DISABLED)
		e2.pack(side=LEFT, fill=X, expand=1)
		
		f1 = Frame(self.wrapper)
		f1.pack(pady=5, fill=X)#-----------------------------------
		
		l1 = Label(f1, text='Valor reajuste: ')
		l1.pack(side=LEFT)
		
		e1 = Entry (f1, textvariable=valor, width=20)
		e1.pack(side=LEFT)
		
		l2 = Label(f1, text='Mes: ')
		l2.pack(side=LEFT)
		
		Cbx2 = Combobox(f1, textvariable=mes, values=meses, width=10)
		Cbx2.set('')
		Cbx2.pack(side=LEFT)
		
		f2 = Frame(self.wrapper)
		f2.pack(pady=5, fill=X)#-----------------------------------
		
		b1 = Button (f2, text="Cancelar", command=cancelar)
		b1.pack(side=RIGHT)
		
		b2 = Button (f2, text="Grabar e Imprimir", command=guardar)
		b2.pack(side=RIGHT)
Beispiel #15
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)
Beispiel #16
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)
Beispiel #17
0
class Application(Frame):
    def __init__(self, master=None, config=config):
        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__,
                                                      id(self)))
        self.display_connections = False
        Frame.__init__(self, master)
        self.grid()
        Style().configure("TFrame", background="#444")
        self.paint_tile = 1
        self.init_ui()

    def init_ui(self):
        self.connections = {}
        self.button_frame = Frame(self)
        self.button_frame.grid(row=0, column=0, columnspan=2)
        self.map_frame = Frame(self)
        self.map_frame.grid(row=1, column=0, padx=5, pady=5)
        self.picker_frame = Frame(self)
        self.picker_frame.grid(row=1, column=1)

        self.button_new = Button(self.button_frame)
        self.button_new["text"] = "New"
        self.button_new["command"] = self.new_map
        self.button_new.grid(row=0, column=0, padx=2)

        self.open = Button(self.button_frame)
        self.open["text"] = "Open"
        self.open["command"] = self.open_map
        self.open.grid(row=0, column=1, padx=2)

        self.save = Button(self.button_frame)
        self.save["text"] = "Save"
        self.save["command"] = self.save_map
        self.save.grid(row=0, column=2, padx=2)

        self.get_map_list()
        self.map_list.grid(row=0, column=3, padx=2)

    def get_map_list(self):
        self.available_maps = sorted(
            m for m in get_available_maps(config=self.config))
        self.map_list = Combobox(self.button_frame,
                                 height=24,
                                 width=24,
                                 values=self.available_maps)
        if len(self.available_maps):
            self.map_list.set(self.available_maps[0])

    def new_map(self):
        self.map_name = None
        self.init_map()
        self.map.blockdata_filename = os.path.join(self.config.map_dir,
                                                   'newmap.blk')
        self.map.blockdata = bytearray([self.paint_tile] * 20 * 20)
        self.map.width = 20
        self.map.height = 20
        self.draw_map()
        self.init_picker()

    def open_map(self):
        self.map_name = self.map_list.get()
        self.init_map()
        self.draw_map()
        self.init_picker()

    def save_map(self):
        if hasattr(self, 'map'):
            if self.map.blockdata_filename:
                filename = tkFileDialog.asksaveasfilename(
                    initialfile=self.map.blockdata_filename)
                with open(filename, 'wb') as save:
                    save.write(self.map.blockdata)
                self.log.info('blockdata saved as {}'.format(
                    self.map.blockdata_filename))
            else:
                self.log.info('dunno how to save this')
        else:
            self.log.info('nothing to save')

    def init_map(self):
        if hasattr(self, 'map'):
            self.map.kill_canvas()
        self.map = Map(self.map_frame, self.map_name, config=self.config)
        self.init_map_connections()

    def draw_map(self):
        self.map.init_canvas(self.map_frame)
        self.map.canvas.pack()  #.grid(row=1,column=1)
        self.map.draw()
        self.map.canvas.bind('<Button-1>', self.paint)
        self.map.canvas.bind('<B1-Motion>', self.paint)

    def init_picker(self):
        self.current_tile = Map(self.button_frame,
                                tileset_id=self.map.tileset_id,
                                config=self.config)
        self.current_tile.blockdata = [self.paint_tile]
        self.current_tile.width = 1
        self.current_tile.height = 1
        self.current_tile.init_canvas()
        self.current_tile.draw()
        self.current_tile.canvas.grid(row=0, column=4, padx=4)

        if hasattr(self, 'picker'):
            self.picker.kill_canvas()
        self.picker = Map(self,
                          tileset_id=self.map.tileset_id,
                          config=self.config)
        self.picker.blockdata = range(len(self.picker.tileset.blocks))
        self.picker.width = 4
        self.picker.height = len(self.picker.blockdata) / self.picker.width
        self.picker.init_canvas(self.picker_frame)

        if hasattr(self.picker_frame, 'vbar'):
            self.picker_frame.vbar.destroy()
        self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL)
        self.picker_frame.vbar.pack(side=RIGHT, fill=Y)
        self.picker_frame.vbar.config(command=self.picker.canvas.yview)

        self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width,
                                                self.picker.canvas_height))
        self.map_frame.update()
        self.picker.canvas.config(height=self.map_frame.winfo_height())
        self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set)
        self.picker.canvas.pack(side=LEFT, expand=True)

        self.picker.canvas.bind('<4>', lambda event: self.scroll_picker(event))
        self.picker.canvas.bind('<5>', lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind('<4>',
                                    lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind('<5>',
                                    lambda event: self.scroll_picker(event))

        self.picker.draw()
        self.picker.canvas.bind('<Button-1>', self.pick_block)

    def scroll_picker(self, event):
        if event.num == 4:
            self.picker.canvas.yview('scroll', -1, 'units')
        elif event.num == 5:
            self.picker.canvas.yview('scroll', 1, 'units')

    def pick_block(self, event):
        block_x = int(self.picker.canvas.canvasx(event.x)) / (
            self.picker.tileset.block_width * self.picker.tileset.tile_width)
        block_y = int(self.picker.canvas.canvasy(event.y)) / (
            self.picker.tileset.block_height * self.picker.tileset.tile_height)
        i = block_y * self.picker.width + block_x
        self.paint_tile = self.picker.blockdata[i]

        self.current_tile.blockdata = [self.paint_tile]
        self.current_tile.draw()

    def paint(self, event):
        block_x = event.x / (self.map.tileset.block_width *
                             self.map.tileset.tile_width)
        block_y = event.y / (self.map.tileset.block_height *
                             self.map.tileset.tile_height)
        i = block_y * self.map.width + block_x
        if 0 <= i < len(self.map.blockdata):
            self.map.blockdata[i] = self.paint_tile
            self.map.draw_block(block_x, block_y)

    def init_map_connections(self):
        if not self.display_connections:
            return
        for direction in self.map.connections.keys():
            if direction in self.connections.keys():
                if hasattr(self.connections[direction], 'canvas'):
                    self.connections[direction].kill_canvas()
            if self.map.connections[direction] == {}:
                self.connections[direction] = {}
                continue
            self.connections[direction] = Map(
                self,
                self.map.connections[direction]['map_name'],
                config=self.config)

            if direction in ['north', 'south']:
                x1 = 0
                y1 = 0
                x2 = x1 + eval(self.map.connections[direction]['strip_length'],
                               self.config.constants)
                y2 = y1 + 3
            else:  # east, west
                x1 = 0
                y1 = 0
                x2 = x1 + 3
                y2 = y1 + eval(self.map.connections[direction]['strip_length'],
                               self.config.constants)

            self.connections[direction].crop(x1, y1, x2, y2)
            self.connections[direction].init_canvas(self.map_frame)
            self.connections[direction].canvas.pack(side={
                'west': LEFT,
                'east': RIGHT
            }[direction])
            self.connections[direction].draw()
Beispiel #18
0
class Application(Frame):
    def __init__(self, master=None, config=config):
        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__,
                                                      id(self)))
        self.display_connections = True

        Frame.__init__(self, master)
        self.pack(fill=BOTH, expand=True)
        Style().configure("TFrame", background="#444")

        self.paint_tile = 1
        self.init_ui()

    def init_ui(self):
        self.connections = {}
        self.button_frame = Frame(self)
        self.button_frame.grid(row=0, column=0, columnspan=2)
        self.map_frame = Frame(self)
        self.map_frame.grid(row=1,
                            column=0,
                            padx=5,
                            pady=5,
                            sticky=N + S + E + W)
        self.picker_frame = Frame(self)
        self.picker_frame.grid(row=1, column=1)

        self.button_new = Button(self.button_frame)
        self.button_new["text"] = "New"
        self.button_new["command"] = self.new_map
        self.button_new.grid(row=0, column=0, padx=2)

        self.menubar = Menu(self)

        menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(label="New")
        menu.add_command(label="Open")
        menu.add_command(label="Save")

        self.open = Button(self.button_frame)
        self.open["text"] = "Open"
        self.open["command"] = self.open_map
        self.open.grid(row=0, column=1, padx=2)

        self.save = Button(self.button_frame)
        self.save["text"] = "Save"
        self.save["command"] = self.save_map
        self.save.grid(row=0, column=2, padx=2)

        self.get_map_list()
        self.map_list.grid(row=0, column=3, padx=2)

    def get_map_list(self):
        self.available_maps = sorted(
            m for m in get_available_maps(config=self.config))
        self.map_list = Combobox(self.button_frame,
                                 height=24,
                                 width=24,
                                 values=self.available_maps)
        if len(self.available_maps):
            self.map_list.set(self.available_maps[0])

    def new_map(self):
        self.map_name = None
        self.init_map()
        self.map.map.blockdata = bytearray([self.paint_tile] * 20 * 20)
        self.map.map.width = 20
        self.map.map.height = 20
        self.draw_map()
        self.init_picker()

    def open_map(self):
        self.map_name = self.map_list.get()
        self.init_map()
        self.draw_map()
        self.init_picker()

    def save_map(self):
        if hasattr(self, 'map'):
            if self.map.map.blk_path:
                initial = self.map.map.blk_path
            else:
                initial = self.config.path
            filename = tkFileDialog.asksaveasfilename(initialfile=initial)
            if filename:
                with open(filename, 'wb') as save:
                    save.write(self.map.map.blockdata)
                self.log.info('blockdata saved as {}'.format(filename))
        else:
            self.log.info('nothing to save')

    def init_map(self):
        if hasattr(self, 'map'):
            self.map.kill_canvas()
        self.map = MapRenderer(self.config,
                               parent=self.map_frame,
                               name=self.map_name)
        self.init_map_connections()

    def draw_map(self):
        self.map.init_canvas(self.map_frame)
        self.map.canvas.pack()  #.grid(row=1,column=1)
        self.map.draw()
        self.map.canvas.bind('<Button-1>', self.paint)
        self.map.canvas.bind('<B1-Motion>', self.paint)

    def init_picker(self):
        """This should really be its own class."""
        self.current_tile = MapRenderer(
            self.config,
            parent=self.button_frame,
            tileset=Tileset(id=self.map.map.tileset.id))
        self.current_tile.map.blockdata = [self.paint_tile]
        self.current_tile.map.width = 1
        self.current_tile.map.height = 1
        self.current_tile.init_canvas()
        self.current_tile.draw()
        self.current_tile.canvas.grid(row=0, column=4, padx=4)

        if hasattr(self, 'picker'):
            self.picker.kill_canvas()
        self.picker = MapRenderer(self.config,
                                  parent=self,
                                  tileset=Tileset(id=self.map.map.tileset.id))
        self.picker.map.blockdata = range(len(self.picker.map.tileset.blocks))
        self.picker.map.width = 4
        self.picker.map.height = len(
            self.picker.map.blockdata) / self.picker.map.width
        self.picker.init_canvas(self.picker_frame)

        if hasattr(self.picker_frame, 'vbar'):
            self.picker_frame.vbar.destroy()
        self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL)
        self.picker_frame.vbar.pack(side=RIGHT, fill=Y)
        self.picker_frame.vbar.config(command=self.picker.canvas.yview)

        self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width,
                                                self.picker.canvas_height))
        self.map_frame.update()

        # overwriting a property is probably a bad idea
        self.picker.canvas_height = self.map_frame.winfo_height()

        self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set)
        self.picker.canvas.pack(side=LEFT, expand=True)

        self.picker.canvas.bind('<4>', lambda event: self.scroll_picker(event))
        self.picker.canvas.bind('<5>', lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind('<4>',
                                    lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind('<5>',
                                    lambda event: self.scroll_picker(event))

        self.picker.draw()
        self.picker.canvas.bind('<Button-1>', self.pick_block)

    def scroll_picker(self, event):
        if event.num == 4:
            self.picker.canvas.yview('scroll', -1, 'units')
        elif event.num == 5:
            self.picker.canvas.yview('scroll', 1, 'units')

    def pick_block(self, event):
        block_x = int(self.picker.canvas.canvasx(
            event.x)) / (self.picker.map.tileset.block_width *
                         self.picker.map.tileset.tile_width)
        block_y = int(self.picker.canvas.canvasy(
            event.y)) / (self.picker.map.tileset.block_height *
                         self.picker.map.tileset.tile_height)
        i = block_y * self.picker.map.width + block_x
        self.paint_tile = self.picker.map.blockdata[i]

        self.current_tile.map.blockdata = [self.paint_tile]
        self.current_tile.draw()

    def paint(self, event):
        block_x = event.x / (self.map.map.tileset.block_width *
                             self.map.map.tileset.tile_width)
        block_y = event.y / (self.map.map.tileset.block_height *
                             self.map.map.tileset.tile_height)
        i = block_y * self.map.map.width + block_x
        if 0 <= i < len(self.map.map.blockdata):
            self.map.map.blockdata[i] = self.paint_tile
            self.map.draw_block(block_x, block_y)

    def init_map_connections(self):
        if not self.display_connections:
            return

        for direction in self.map.map.connections.keys():

            if direction in self.connections.keys():
                if hasattr(self.connections[direction], 'canvas'):
                    self.connections[direction].kill_canvas()

            if self.map.map.connections[direction] == {}:
                self.connections[direction] = {}
                continue

            self.connections[direction] = MapRenderer(
                self.config,
                parent=self,
                name=self.map.map.connections[direction]['map_name'])

            attrs = self.map.map.connections[direction]
            if direction in ['north', 'south']:
                if direction == 'north':
                    x1 = 0
                    if self.config.version == 'red':
                        y1 = eval(attrs['other_height'],
                                  self.config.constants) - 3
                    elif self.config.version == 'crystal':
                        y1 = eval(attrs['map'] + '_HEIGHT',
                                  self.config.constants) - 3
                else:  # south
                    x1 = 0
                    y1 = 0
                x2 = x1 + eval(attrs['strip_length'], self.config.constants)
                y2 = y1 + 3
            else:
                if direction == 'east':
                    x1 = 0
                    y1 = 0
                else:  # west
                    x1 = -3
                    y1 = 1
                x2 = x1 + 3
                y2 = y1 + eval(attrs['strip_length'], self.config.constants)

            self.connections[direction].init_canvas(self.map_frame)
            self.connections[direction].canvas.pack(side={
                'north': TOP,
                'south': BOTTOM,
                'west': LEFT,
                'east': RIGHT
            }[direction])
            self.connections[direction].map.crop(x1, y1, x2, y2)
            self.connections[direction].draw()
Beispiel #19
0
class LoggerDialog(Toplevel):
    def __init__(self, master, customers, payments, refresh):
        Toplevel.__init__(self,master)

        self.root = master
        self.refresh = refresh

        self.title("Check In")
        self.iconname = "Check In"

        self.name = StringVar() # variable for customer
        self.customers = customers # customers object
        self.payments = payments
        self.names = []
        self.workout = StringVar()
        self.workouts = []
        self.workouts_form = []
        self.date = StringVar()
        self.date.set(strftime("%m/%d/%Y"))
        self.refresh_time = 15 # in minutes
        self.output = '' # for the output label at the bottom
        self.schedule = Schedule()

        self.logger = Logger() #throws IOError if file is open

        inf = Frame(self)
        inf.pack(padx=10,pady=10,side='top')
        Label(inf, text="Name:").grid(row=0,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text='Date:').grid(row=1,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text="Workout:").grid(row=2,column=0,sticky=E,ipady=2,pady=2,padx=10)

        self.name_cb = Combobox(inf, textvariable=self.name, width=30,
                                values=self.names)
        self.name_cb.grid(row=0,column=1,sticky=W,columnspan=2)
        self.date_ent = Entry(inf, textvariable=self.date)
        self.date_ent.grid(row=1,column=1,sticky=W)
        self.date_ent.bind('<FocusOut>', self.update_workouts)
        Button(inf,text='Edit', command=self.enable_date_ent).grid(row=1,column=2,sticky=E)
        self.workout_cb = Combobox(inf, textvariable=self.workout, width=30,
                                   values=self.workouts_form,state='readonly')
        self.workout_cb.grid(row=2,column=1,sticky=W,columnspan=2)

        self.log_btn=Button(inf,text="Log Workout",command=self.log,width=12)
        self.log_btn.grid(row=3,column=1,columnspan=2,pady=4,sticky='ew')
        
        stf = Frame(self)
        stf.pack(padx=10,pady=10,fill='x',side='top')
        self.scrolled_text = ScrolledText(stf,height=15,width=50,wrap='word',state='disabled')
        self.scrolled_text.pack(expand=True,fill='both')

        self.update_workouts()
        self.update_names()

        self.bind('<Return>',self.log)
        self.name_cb.focus_set()  # set the focus here when created

        #disable the date field
        self.disable_date_ent()

        #start time caller
        self.time_caller()

    def output_text(self,outstr):
        self.scrolled_text['state'] = 'normal'
        self.scrolled_text.insert('end',outstr)
        self.scrolled_text.see('end')
        self.scrolled_text['state'] = 'disabled'

    def log(self, e=None):
        #check to see if name is blank
        logged = False
        if self.name.get() == '':
            self.output_text("! - Please select your name.\n")
        elif self.workout.get() not in self.workouts_form:
            self.output_text("! - Select valid workout.\n")
        elif self.name.get() not in self.names: # new customer
            self.new_customer_error()
        else: # log the workout
            name = self.name.get().split(' ',2)
            (line, r) = self.customers.find(name[2],name[0],name[1])
            name_str = str(self.name.get())
            date = datetime.strptime(str(self.date.get()),'%m/%d/%Y')

            if not line:
                self.output_text("!! - No record: " + self.name.get() + ".\n")

            while (not logged):
                try:
                    self.logger.log(self.workouts[self.workout_cb.current()][0],
                                    self.workouts[self.workout_cb.current()][1],
                                    name_str, day=date)
                    logged = True
                except IOError:
                    showerror("Error writting to file", "Please close " + self.logger.filename + " and press OK.")


            if logged:
                self.output_text(self.name.get() + " - " + line[3] + "\n")
                logged_payment = False
                while(not logged_payment):
                    try:
                        if line[3] == 'Monthly':
                            payment_due = self.payments.next_payment_due(name_str)
                            if payment_due < datetime.today():
                                self.output_text("$ - Please pay your monthly dues.\n")
                            else:
                                self.output_text("$ - Next payment due: " + payment_due.strftime("%B %d, %Y\n"))
                        elif line[3] == 'Punch Card':
                            punch = self.payments.punch(name_str)
                            if punch == 0:
                                self.output_text("$ - Last punch on card, please purchase another.\n")
                            elif not punch:
                                self.output_text("$ - Please purchase another punch card.\n")
                            else:
                                self.output_text("$ - You have " + str(punch) + " remaining workouts on your card.\n")
                        elif line[3] == 'Drop In':
                            self.payments.drop_in(name_str, date)
                            self.output_text("$ - Drop In payment logged.\n")
                        logged_payment = True
                    except IOError:
                        # this is bad, you logged a workout and you failed to log payment
                        showerror("Error writting to file", "Please close " + self.payments.filename + " and press OK.")
                    else:
                        #exception not raised
                        try: #accessing log file here
                            workout_count = str(workouts_this_month(name_str,self.logger.filename,date.strftime("%B"))) 
                            self.output_text("Workouts you've completed this month: " + workout_count + "\n")
                        except IOError:
                            showerror("Error reading from file", "Please close " + self.logger.filename + " and press OK.")

                self.refresh()
            
    def new_customer_error(self):
        self.ncd = NewCustomerDialog(self,self.customers,self.refresh)
        if askquestion(title="New Customer?",
            message="Add new customer: " + self.name.get(),
            parent = self) == 'yes':

            temp = self.name.get().split(' ')
            self.ncd.fname.set(temp[0])
            if len(temp) == 2:
                self.ncd.lname.set(temp[1])
            elif len(temp) == 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(temp[2])
            elif len(temp) > 3:
                self.ncd.mname.set(temp[1])
                self.ncd.lname.set(' '.join(temp[2:4]))

            self.ncd.show()

        if self.ncd.new_customer_name:
            self.add_name(self.ncd.new_customer_name)
            self.output_text("+ - " + self.ncd.new_customer_name + " added.\n")

    def disable_date_ent(self, e=None):
        self.date_ent['state'] = 'disabled'

    def enable_date_ent(self, e=None):
        self.date_ent['state'] = 'normal'
        
    def time_caller(self):
        #updates every 15 min automatically
        msec = self.refresh_time * 6000

        self.update_time_now() #update time to current time
        self.set_workout_now()
        self.update_workouts() #update the workouts
        
        self.after(msec, self.time_caller) #call again

    def update_time_now(self):
        self.enable_date_ent()
        self.date.set(strftime("%m/%d/%Y"))

    def set_workout_now(self):
        #set workout field
        if len(self.workouts) == 0:
            self.disable_date_ent()
            return #no workouts
        index = 0
        now = datetime.today()
        for i, workout in enumerate(self.workouts):
            test = datetime.combine(date.today(),workout[0])
            if now < (test - timedelta(minutes=15)):
                index = i
                break
        self.workout_cb.current(index)
        self.disable_date_ent()
            
    def update_workouts(self, e=None):
        try:
            self.populate_workouts()
            self.workout_cb['values'] = self.workouts_form
        except ValueError:
            self.workout.set(' Enter Valid Date ')
        if len(self.workouts) > 0 and e:
            self.workout_cb.current(0)
            
    def populate_workouts(self):
        today = datetime.strptime(str(self.date.get()), "%m/%d/%Y") #get date
        dow = self.schedule.weekday_to_str(today.weekday()) #get dow string

        self.workouts = self.schedule.get_wkday(dow)
        self.workouts_form = []
        for w in self.workouts:
            self.workouts_form.append(w[0].strftime("%H:%M") + ' - ' + w[1])
        if len(self.workouts) == 0:
            self.workout.set(' No workouts today ')

    def update_names(self):
        self.populate_names()
        if len(self.names) == 0: self.names = ['']
        self.name_cb['values'] = self.names
        self.name_cb.set(' ')

    def add_name(self, name):
        self.names.append(name)
        split_names = [x.split(' ') for x in self.names]
        split_names.sort(key = lambda x: ' '.join([x[2],x[0],x[1]]))
        self.names = [' '.join(x) for x in split_names]
        self.name_cb['values'] = self.names
        self.name.set(name)
        
    def populate_names(self):
        try:
            clist = self.customers.get_list()
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.names = []
        for line in clist:
            self.names.append(' '.join([line[1],line[2],line[0]]))

    def find_line(self, name):
        [fname, mname, lname] = name.split(' ')
        try:
            return self.customers.find(lname, fname, mname)
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return None
Beispiel #20
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg=None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W + N, pady=4, padx=5)

        check_box = {"work": IntVar(), "boost": IntVar()}

        check1 = Checkbutton(self,
                             text="work-Mode",
                             variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self,
                             text="boost games",
                             variable=check_box["boost"])
        check2.grid(row=7, column=1)

        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand=self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(working_bans, self.entry.get(), self.
                                        entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(boosted, self.entry2.get(), self.
                                        entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(
            self,
            text="Remove",
            command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_to_list(degraded, self.entry3.get(), self.
                                        entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self,
                                text="Remove",
                                command=lambda: remove_from_list(
                                    music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(
            self,
            text="Add",
            command=lambda: add_music(music_list, self.entry5.get(
            ), self.entry4.get(), self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)

        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self,
                       text="TaskManager",
                       command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(
            self,
            text="start",
            command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Beispiel #21
0
class MainFrame(Frame):
    def __init__(self, parent, stdoutq):
        Frame.__init__(self, parent)

        self.parent = parent
        self.width = 750
        self.height = 450
        self.title = ximaexport.__version__
        self.stdoutq = stdoutq

        self.initUI()

        self.hasdb = False
        self.hasout = False
        self.exit = False

        self.path_frame = self.addPathFrame()
        self.action_frame = self.addActionFrame()
        self.message_frame = self.addMessageFrame()
        self.printStr()

        self.stateq = Queue.Queue()

    def centerWindow(self):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - self.width) / 2
        y = (sh - self.height) / 2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))

    def initUI(self):
        self.parent.title(self.title)
        self.style = Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH, expand=True)
        self.centerWindow()

    def printStr(self):
        while self.stdoutq.qsize() and self.exit == False:
            try:
                msg = self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END, msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100, self.printStr)

    def checkReady(self):

        if self.hasdb and self.hasout:
            self.start_button.configure(state=tk.NORMAL)
            #print('XimaExport Ready.')
            printch('XimaExport 就绪.')
        else:
            self.start_button.configure(state=tk.DISABLED)

    def addPathFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5)

        frame.columnconfigure(1, weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry = tk.Entry(frame)
        self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8)

        self.db_button = tk.Button(frame,
                                   text=dgbk('打开'),
                                   command=self.openFile)
        self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry = tk.Entry(frame)
        self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8)
        self.out_button = tk.Button(frame,
                                    text=dgbk('选择'),
                                    command=self.openDir)
        self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E)

    def openDir(self):
        self.out_entry.delete(0, tk.END)
        dirname = askdirectory()
        self.out_entry.insert(tk.END, dirname)
        if len(dirname) > 0:
            #print('Output folder: %s' %dirname)
            printch('输出到文件夹:')
            print('   ' + dirname)
            self.hasout = True
            self.checkReady()

    def openFile(self):
        self.db_entry.delete(0, tk.END)
        ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')]
        filename = askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END, filename)
        if len(filename) > 0:
            #print('Database file: %s' %filename)
            printch('数据文件:')
            print('   ' + filename)
            self.probeAlbums()

    def probeAlbums(self):
        dbfile = self.db_entry.get()
        try:
            db = sqlite3.connect(dbfile)
            df = ximaexport.getData(db)
            self.albumlist = ximaexport.getAlbumList(df, None)  #(id, name)
            self.albumnames = ['All'] + [ii[1] for ii in self.albumlist
                                         ]  #names to display
            self.albummenu['values'] = tuple(self.albumnames)
            self.albummenu.current(0)
            db.close()

            self.hasdb = True
            self.checkReady()

        except Exception as e:
            #print('Failed to recoganize the given database file.')
            printch('无法识别sqlite数据文件.')
            print(e)

    def addActionFrame(self):

        frame = Frame(self, relief=tk.RAISED, borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        #label=tk.Label(frame,text='Actions:',bg='#bbb')
        #label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        frame.columnconfigure(0, weight=1)

        #---------------------2nd row---------------------
        subframe = Frame(frame)
        subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Album options-------------------
        albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\
                bg='#bbb')
        albumlabel.pack(side=tk.LEFT, padx=8)

        self.album = tk.StringVar()
        self.albumnames = [
            'All',
        ]
        self.albummenu=Combobox(subframe,textvariable=\
                self.album,values=self.albumnames,state='readonly')
        self.albummenu.current(0)
        self.albummenu.bind('<<ComboboxSelected>>', self.setAlbum)
        self.albummenu.pack(side=tk.LEFT, padx=8)

        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text=dgbk('退出'),\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT, padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''

        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text=dgbk('开始'),\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT, pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text=dgbk('帮助'),\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT, padx=8)

    def setAlbum(self, x):
        import json
        self.albummenu.selection_clear()
        self.album = self.albummenu.get()
        self.albummenu.set(self.album)
        if self.album == 'All':
            #print('Work on all albums.')
            printch('导出所有专辑.')
        else:
            #print('Select album: '+self.album)
            printch('导出所选专辑:')
            print('   ' + self.album)

    def showHelp(self):
        helpstr = dgbk('''\n\n
导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n
1. 找到手机/pad中的喜马拉雅数据文件夹:\n
    (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n
    (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n
2. 运行ximaexport-gui.exe。\n
    在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n
    在 “导出到文件夹”一栏,选择音频存储位置。\n
    在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n
    点击“开始”开始处理。
''')

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())

    def start(self):
        dbfile = self.db_entry.get()
        outdir = self.out_entry.get()
        self.album = self.albummenu.get()

        self.out_button.configure(state=tk.DISABLED)
        self.start_button.configure(state=tk.DISABLED)
        self.help_button.configure(state=tk.DISABLED)
        self.albummenu.configure(state=tk.DISABLED)
        self.messagelabel.configure(text=dgbk('信息 (处理中...)'))

        album = None if self.album == 'All' else self.album

        args = [dbfile, outdir, album, True]

        self.workthread = WorkThread('work', False, self.stateq)
        self.workthread.deamon = True

        self.workthread.args = args
        self.workthread.start()
        self.reset()

    def reset(self):
        while self.stateq.qsize() and self.exit == False:
            try:
                msg = self.stateq.get()
                if msg == 'done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.albummenu.configure(state='readonly')
                    self.messagelabel.configure(text=dgbk('消息'))
                    return
            except Queue.Empty:
                pass
        self.after(100, self.reset)

    def stop(self):
        #self.workthread.stop()
        pass

    def addMessageFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel = tk.Label(frame, text=dgbk('消息'), bg='#bbb')
        self.messagelabel.pack(side=tk.TOP, fill=tk.X)

        self.text = tk.Text(frame)
        self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.text.height = 10

        scrollbar = tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #22
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=850
        self.height=650
        self.title=menotexport.__version__
        self.stdoutq=stdoutq

        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.hasaction=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()
        #self.workproc=Pool(1)




    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)


    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1 or self.isbib.get()==1:
            self.hasaction=True
        else:
            self.hasaction=False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('# <Menotexport>: Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text='Open',command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        hint='''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text='Choose',command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            print('# <Menotexport>: Output folder: %s' %dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALL files','*')]
        initialdir='~/.local/share/data/Mendeley Ltd./Mendeley Desktop'
        initialdir=os.path.expanduser(initialdir)
        if os.path.isdir(initialdir):
            filename=askopenfilename(filetypes=ftypes,initialdir=initialdir)
        else:
            filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            print('# <Menotexport>: Database file: %s' %filename)
            self.probeFolders()


    def probeFolders(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            self.menfolderlist=menotexport.getFolderList(db,None)   #(id, name)
            self.foldernames=['All']+[ii[1] for ii in self.menfolderlist] #names to display
            self.foldersmenu['values']=tuple(self.foldernames)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            print('# <Menotexport>: Failed to recoganize the given database file.') 
            print(e)





    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label=tk.Label(frame,text='Actions:',bg='#bbb')
        label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        self.isexport=tk.IntVar()
        self.ishighlight=tk.IntVar()
        self.isnote=tk.IntVar()
        self.isbib=tk.IntVar()
        self.isris=tk.IntVar()
        self.isseparate=tk.IntVar()
        self.iszotero=tk.IntVar()
        self.iscustomtemp=tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_bib=tk.Checkbutton(frame,\
                text='Export .bib',\
                variable=self.isbib,command=self.doBib)

        self.check_ris=tk.Checkbutton(frame,\
                text='Export .ris',\
                variable=self.isris,command=self.doRis)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        self.check_iszotero=tk.Checkbutton(frame,\
                text='For import to Zotero',\
                variable=self.iszotero,command=self.doIszotero,\
                state=tk.DISABLED)

        self.check_custom_template=tk.Checkbutton(frame,\
                text='Use custom template (experimental)',\
                variable=self.iscustomtemp,command=self.doCustomTemp,\
                state=tk.DISABLED)

        frame.columnconfigure(0,weight=1)

        self.check_export.grid(row=1,column=1,padx=8,sticky=tk.W)
        self.check_highlight.grid(row=1,column=2,padx=8,sticky=tk.W)
        self.check_note.grid(row=1,column=3,padx=8,sticky=tk.W)
        self.check_bib.grid(row=2,column=1,padx=8,sticky=tk.W)
        self.check_ris.grid(row=2,column=2,padx=8,sticky=tk.W)
        self.check_separate.grid(row=2,column=3,padx=8,sticky=tk.W)
        self.check_iszotero.grid(row=3,column=1,padx=8,sticky=tk.W)
        self.check_custom_template.grid(row=3,column=2,padx=8,sticky=tk.W)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder=tk.StringVar()
        self.menfolderlist=['All',]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT,padx=8)
        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)



    def setfolder(self,x):
        self.foldersmenu.selection_clear()
        self.menfolder=self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder=='All':
            print('# <Menotexport>: Work on all folders.')
        else:
            print('# <Menotexport>: Select Mendeley folder: '+str(self.menfolder))



    def doExport(self):
        if self.isexport.get()==1:
            print('# <Menotexport>: Export annotated PDFs.')
        else:
            print('# <Menotexport>: Dont export annotated PDFs.')

        self.checkReady()



    def doHighlight(self):
        if self.ishighlight.get()==1:
            print('# <Menotexport>: Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract highlighted texts.')
            if self.isnote.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get()==1:
            print('# <Menotexport>: Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract notes.')
            self.check_separate.state=tk.DISABLED
            if self.ishighlight.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()
        self.checkReady()

    def doBib(self):
        if self.isbib.get()==1:
            print('# <Menotexport>: Export to .bib file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .bib file.')
            if self.isris.get()==0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doRis(self):
        if self.isris.get()==1:
            print('# <Menotexport>: Export to .ris file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .ris file.')
            if self.isbib.get()==0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doSeparate(self):
        if self.isseparate.get()==1:
            print('# <Menotexport>: Save annotations separately.')
        else:
            print('# <Menotexport>: Save all annotations to single file.')

    def doIszotero(self):
        if self.iszotero.get()==1:
            print('# <Menotexport>: Save .bib/.ris file in Zotero preferred format.')
        else:
            print('# <Menotexport>: Save .bib/.ris file to default format.')

    def doCustomTemp(self):
        if self.iscustomtemp.get()==1:
            print('# <Menotexport>: Use custom template for exported annotations.')
        else:
            print('# <Menotexport>: Use default template for exported annotations.')



    def showHelp(self):
        helpstr='''
%s\n\n
- Export PDFs: Bulk export PDFs.\n
- Extract highlights: Extract highlighted texts and output to txt files.\n
- Extract notes: Extract notes and output to txt files.\n
- Export .bib: Export meta-data and annotations to .bib files.\n
- Export .ris: Export meta-data and annotations to .ris files.\n
- For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- Use custom annotation template: Use a custom template to format the exported annotations.
  See annotation_template.py for details.
- See README.md for more info.\n
''' %self.title

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())




    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        self.menfolder=self.foldersmenu.get()

        # get (folderid, folder) for folder
        for ii in self.menfolderlist:
            if ii[1]==self.menfolder:
                folder_sel=[ii[0],ii[1].split('/')[-1]]

        action=[]
        if self.isexport.get()==1:
            action.append('p')
        if self.ishighlight.get()==1:
            action.append('m')
        if self.isnote.get()==1:
            action.append('n')
        if self.isbib.get()==1:
            action.append('b')
        if self.isris.get()==1:
            action.append('r')
        if self.isseparate.get()==1:
            separate=True
        else:
            separate=False
        if self.iszotero.get()==1:
            iszotero=True
        else:
            iszotero=False
        if self.iscustomtemp.get()==1:
            action.append('t')

            
        if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_bib.configure(state=tk.DISABLED)
            self.check_ris.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
            self.check_iszotero.configure(state=tk.DISABLED)
            self.check_custom_template.configure(state=tk.DISABLED)
            self.messagelabel.configure(text='Message (working...)')

            folder=None if self.menfolder=='All' else folder_sel

            args=[dbfile,outdir,action,folder,separate,iszotero,True]

            self.workthread=WorkThread('work',False,self.stateq)
            self.workthread.deamon=True

            self.workthread.args=args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''



    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_bib.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.check_iszotero.configure(state=tk.NORMAL)
                    self.check_custom_template.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text='Message',bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #23
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)
class Application(Frame):
    def __init__(self, master=None, config=config):
        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self)))
        self.display_connections = False
        Frame.__init__(self, master)
        self.grid()
        Style().configure("TFrame", background="#444")
        self.paint_tile = 1
        self.init_ui()

    def init_ui(self):
        self.connections = {}
        self.button_frame = Frame(self)
        self.button_frame.grid(row=0, column=0, columnspan=2)
        self.map_frame = Frame(self)
        self.map_frame.grid(row=1, column=0, padx=5, pady=5)
        self.picker_frame = Frame(self)
        self.picker_frame.grid(row=1, column=1)

        self.button_new = Button(self.button_frame)
        self.button_new["text"] = "New"
        self.button_new["command"] = self.new_map
        self.button_new.grid(row=0, column=0, padx=2)

        self.open = Button(self.button_frame)
        self.open["text"] = "Open"
        self.open["command"] = self.open_map
        self.open.grid(row=0, column=1, padx=2)

        self.save = Button(self.button_frame)
        self.save["text"] = "Save"
        self.save["command"] = self.save_map
        self.save.grid(row=0, column=2, padx=2)

        self.get_map_list()
        self.map_list.grid(row=0, column=3, padx=2)


    def get_map_list(self):
        self.available_maps = sorted(m for m in get_available_maps(config=self.config))
        self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps)
        if len(self.available_maps):
            self.map_list.set(self.available_maps[0])

    def new_map(self):
        self.map_name = None
        self.init_map()
        self.map.blockdata_filename = os.path.join(self.config.map_dir, 'newmap.blk')
        self.map.blockdata = bytearray([self.paint_tile] * 20 * 20)
        self.map.width = 20
        self.map.height = 20
        self.draw_map()
        self.init_picker()

    def open_map(self):
        self.map_name = self.map_list.get()
        self.init_map()
        self.draw_map()
        self.init_picker()

    def save_map(self):
        if hasattr(self, 'map'):
            if self.map.blockdata_filename:
                filename = tkFileDialog.asksaveasfilename(initialfile=self.map.blockdata_filename)
                with open(filename, 'wb') as save:
                    save.write(self.map.blockdata)
                self.log.info('blockdata saved as {}'.format(self.map.blockdata_filename))
            else:
                self.log.info('dunno how to save this')
        else:
            self.log.info('nothing to save')

    def init_map(self):
        if hasattr(self, 'map'):
            self.map.kill_canvas()
        self.map = Map(self.map_frame, self.map_name, config=self.config)
        self.init_map_connections()

    def draw_map(self):
        self.map.init_canvas(self.map_frame)
        self.map.canvas.pack() #.grid(row=1,column=1)
        self.map.draw()
        self.map.canvas.bind('<Button-1>', self.paint)
        self.map.canvas.bind('<B1-Motion>', self.paint)

    def init_picker(self):
        self.current_tile = Map(self.button_frame, tileset_id=self.map.tileset_id, config=self.config)
        self.current_tile.blockdata = [self.paint_tile]
        self.current_tile.width = 1
        self.current_tile.height = 1
        self.current_tile.init_canvas()
        self.current_tile.draw()
        self.current_tile.canvas.grid(row=0, column=4, padx=4)

        if hasattr(self, 'picker'):
            self.picker.kill_canvas()
        self.picker = Map(self, tileset_id=self.map.tileset_id, config=self.config)
        self.picker.blockdata = range(len(self.picker.tileset.blocks))
        self.picker.width = 4
        self.picker.height = len(self.picker.blockdata) / self.picker.width
        self.picker.init_canvas(self.picker_frame)

        if hasattr(self.picker_frame, 'vbar'):
            self.picker_frame.vbar.destroy()
        self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL)
        self.picker_frame.vbar.pack(side=RIGHT, fill=Y)
        self.picker_frame.vbar.config(command=self.picker.canvas.yview)

        self.picker.canvas.config(scrollregion=(0,0,self.picker.canvas_width, self.picker.canvas_height))
        self.map_frame.update()
        self.picker.canvas.config(height=self.map_frame.winfo_height())
        self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set)
        self.picker.canvas.pack(side=LEFT, expand=True)

        self.picker.canvas.bind('<4>', lambda event : self.scroll_picker(event))
        self.picker.canvas.bind('<5>', lambda event : self.scroll_picker(event))
        self.picker_frame.vbar.bind('<4>', lambda event : self.scroll_picker(event))
        self.picker_frame.vbar.bind('<5>', lambda event : self.scroll_picker(event))

        self.picker.draw()
        self.picker.canvas.bind('<Button-1>', self.pick_block)

    def scroll_picker(self, event):
        if event.num == 4:
            self.picker.canvas.yview('scroll', -1, 'units')
        elif event.num == 5:
            self.picker.canvas.yview('scroll', 1, 'units')


    def pick_block(self, event):
        block_x = int(self.picker.canvas.canvasx(event.x)) / (self.picker.tileset.block_width * self.picker.tileset.tile_width)
        block_y = int(self.picker.canvas.canvasy(event.y)) / (self.picker.tileset.block_height * self.picker.tileset.tile_height)
        i = block_y * self.picker.width + block_x
        self.paint_tile = self.picker.blockdata[i]

        self.current_tile.blockdata = [self.paint_tile]
        self.current_tile.draw()

    def paint(self, event):
        block_x = event.x / (self.map.tileset.block_width * self.map.tileset.tile_width)
        block_y = event.y / (self.map.tileset.block_height * self.map.tileset.tile_height)
        i = block_y * self.map.width + block_x
        if 0 <= i < len(self.map.blockdata):
            self.map.blockdata[i] = self.paint_tile
            self.map.draw_block(block_x, block_y)

    def init_map_connections(self):
        if not self.display_connections:
            return
        for direction in self.map.connections.keys():
            if direction in self.connections.keys():
                if hasattr(self.connections[direction], 'canvas'):
                    self.connections[direction].kill_canvas()
            if self.map.connections[direction] == {}:
                self.connections[direction] = {}
                continue
            self.connections[direction] = Map(self, self.map.connections[direction]['map_name'], config=self.config)

            if direction in ['north', 'south']:
                x1 = 0
                y1 = 0
                x2 = x1 + eval(self.map.connections[direction]['strip_length'], self.config.constants)
                y2 = y1 + 3
            else: # east, west
                x1 = 0
                y1 = 0
                x2 = x1 + 3
                y2 = y1 + eval(self.map.connections[direction]['strip_length'], self.config.constants)

            self.connections[direction].crop(x1, y1, x2, y2)
            self.connections[direction].init_canvas(self.map_frame)
            self.connections[direction].canvas.pack(side={'west':LEFT,'east':RIGHT}[direction])
            self.connections[direction].draw()
Beispiel #25
0
	def __init__(self, parent, controller):
		Frame.__init__(self, parent)

		#VARIABLES GLOBALES
		global cedula, titulo, ingreso, rsocial, residencia, nombres, apellidos, direccion, telefono, oficina, tel, telfax, correo, cumpleanos, dia, mes, envio, celular, tipopersona, comision, retefuente, reteiva, gcontribuyente, gfactura, gcheque, reprecc, reprenombres, repredireccion, repretelefono, repreoficina, repretel, reprebanco, repretcuenta, reprenumcuenta, tit1cc, tit1nombres, tit1banco, tit1tcuenta, tit1numcuenta, tit2cc, tit2nombres, tit2banco, tit2tcuenta, tit2numcuenta, lb, note, popmenu, busqueda, dato, E
		#INSTANCIEAS DE LOS WIDGETS
		global ccE, refE, dateinE, socialE, cityE, nameE, lnameE, adressE, phoneE, officeE, officetelE, telfaxE, emailE, birthdayE, birthdayCbx, mailE, mobileE, personR1, personR2, comisionE, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc0E, name0E, adress0E, phone0E, office0E, officetel0E, bank0Cbx, tbank0Cbx, tcuenta0E, cc1E, name1E, bank1Cbx, tbank1Cbx, tcuenta1E, cc2E, name2E, bank2Cbx, tbank2Cbx, tcuenta2E, add, update, delete, clean
		global info, lists, _propietarios
		
		_propietarios = dict()
		lists = []
			
		#Variables
		cedula = StringVar()
		titulo = StringVar()
		ingreso = StringVar()
		rsocial = StringVar()
		residencia = StringVar()
		nombres = StringVar()
		apellidos = StringVar()
		direccion = StringVar()
		telefono = StringVar()
		oficina = StringVar()
		tel = StringVar()
		telfax = StringVar()
		correo = StringVar()
		dia = IntVar()
		mes = StringVar()
		envio = StringVar()
		celular = StringVar()
		tipopersona = IntVar()
		comision = DoubleVar()
		retefuente = IntVar()
		reteiva = IntVar()
		gcontribuyente = IntVar()
		gfactura = IntVar()
		gcheque = IntVar()
		notas = StringVar()
		
		#----------------------------
		
		reprecc = StringVar()
		reprenombres = StringVar()
		repredireccion = StringVar()
		repretelefono = StringVar()
		repreoficina = StringVar()
		repretel = StringVar()
		reprebanco = StringVar()
		repretcuenta = StringVar()
		reprenumcuenta = StringVar()
		
		tit1cc = StringVar()
		tit1nombres = StringVar()
		tit1banco = StringVar()
		tit1tcuenta = StringVar()
		tit1numcuenta = StringVar()
		
		tit2cc = StringVar()
		tit2nombres = StringVar()
		tit2banco = StringVar()
		tit2tcuenta = StringVar()
		tit2numcuenta = StringVar()
		
		meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto","Septiembre", "Octubre", "Noviembre", "Diciembre"]
		tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"]

		tbanktype = ['Corriente','Ahorro']
		
		#BUSQUEDA = ["Nombre","CC/Nit"]
		busqueda = StringVar()
		busqueda.trace("w", lambda name, index, mode: buscar())
		info = IntVar()
		#eleccion = IntVar()
		dato = StringVar()
		
		# MENU DEL MOUSE
		
		popmenu = Menu(self, tearoff=0)
		popmenu.add_command(label="Imprimir", command=hello)
		popmenu.add_command(label="Cargar", command=modificar)
		popmenu.add_command(label="Eliminar", command=borrar)
		#popmenu.add_separator()
		popmenu.bind('<Escape>', release)

		#WIDGETS
		
		#========================= HEADER ==============================
		
		self.header = Label(self, text="GESTIÓN DE PROPIETARIOS", font="bold")
		self.header.pack(pady=20, side=TOP)

		#========================== WRAPPER ============================
		#Contiene los Notebooks con los campos formulario

		self.wrapper = Frame (self)
		self.wrapper.pack(side=LEFT, fill=Y)
		#Esto centro el wrapper
		#self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)
		
		#================ NOTEBOOK =============>
		
		self.nb = Notebook(self.wrapper)
		
		#-----------------------> TAB 1
		
		self.tab1 = Frame (self.nb)
		
		self.f0 = Frame(self.tab1)#Para dejar espacio entre Tab y Label
		self.f0.pack(fill=X, pady=10)#-------------------------------
		
		#========================= PERSONALES ==========================
		
		self.f1 = Frame(self.tab1)#-------------------------------
		self.f1.pack(pady=5,fill=X)
		
		self.ccL = Label(self.f1, text='CC/Nit:')
		self.ccL.pack(side=LEFT)
		ccE = Entry(self.f1, textvariable=cedula)
		ccE.pack(side=LEFT, fill=X, expand=1)
		ccE.focus_set()

		self.refL = Label(self.f1, text='Título:')
		self.refL.pack(side=LEFT)
		refE = Entry(self.f1, textvariable=titulo, width=10)
		refE.pack(side=LEFT)
		#refE.bind("<KeyRelease>", caps)

		self.dateinL = Label(self.f1, text='Fecha Ingreso:')
		self.dateinL.pack(side=LEFT)
		dateinE = Entry(self.f1, textvariable=ingreso, width=10, state=DISABLED)
		ingreso.set("0000-00-00")
		dateinE.pack(side=LEFT)

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

		self.socialL = Label(self.f2, text='Razón Social:')
		self.socialL.pack(side=LEFT)
		socialE = Entry(self.f2, textvariable=rsocial)
		socialE.pack(side=LEFT, fill=X, expand=1)
		socialE.bind("<KeyRelease>", caps)

		self.cityL = Label(self.f2, text='Ciudad de residencia:')
		self.cityL.pack(side=LEFT)
		cityE = Entry(self.f2, textvariable=residencia, width=15)
		cityE.pack(side=LEFT)
		cityE.bind("<KeyRelease>", caps)

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

		self.nameL = Label(self.f3, text='Nombres:')
		self.nameL.pack(side=LEFT)
		nameE = Entry(self.f3, textvariable=nombres)
		nameE.pack(side=LEFT, fill=X, expand=1)
		nameE.bind("<KeyRelease>", caps)

		self.lnameL = Label(self.f3, text='Apellidos:')
		self.lnameL.pack(side=LEFT)
		lnameE = Entry(self.f3, textvariable=apellidos)
		lnameE.pack(side=LEFT, fill=X, expand=1)
		lnameE.bind("<KeyRelease>", caps)

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

		self.adressL = Label(self.f4, text='Dir. Casa:')
		self.adressL.pack(side=LEFT)
		adressE = Entry(self.f4, textvariable=direccion)
		adressE.pack(side=LEFT, fill=X, expand=1)
		adressE.bind("<KeyRelease>", caps)

		self.phoneL = Label(self.f4, text='Tel:')
		self.phoneL.pack(side=LEFT)
		phoneE = Entry(self.f4, textvariable=telefono, width=20)
		phoneE.pack(side=LEFT)

		self.f5 = Frame(self.tab1)
		self.f5.pack(pady=5,fill=X)#------------------------------------
		
		self.officeL = Label(self.f5, text='Dir. Oficina:')
		self.officeL.pack(side=LEFT)
		officeE = Entry(self.f5, textvariable=oficina, width=20)
		officeE.pack(side=LEFT, fill=X, expand=1)
		officeE.bind("<KeyRelease>", caps)

		self.officetelL = Label(self.f5, text='Tel:')
		self.officetelL.pack(side=LEFT)
		officetelE = Entry(self.f5, textvariable=tel, width=15)
		officetelE.pack(fill=X, side=LEFT)

		self.telfaxL = Label(self.f5, text='Tel. Fax:')
		self.telfaxL.pack(side=LEFT)
		telfaxE = Entry(self.f5, textvariable=telfax, width=10)
		telfaxE.pack(side=LEFT)

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

		self.emailL = Label(self.f6, text='Email:')
		self.emailL.pack(side=LEFT)
		emailE = Entry(self.f6, textvariable=correo, width=30)
		emailE.pack(side=LEFT)

		self.birthdayL = Label(self.f6, text='Cumpleaños:')
		self.birthdayL.pack(side=LEFT)

		self.birthdayL2 = Label(self.f6, text='Día:')
		self.birthdayL2.pack(padx=5,side=LEFT)
		
		#s = Spinbox(self.f6, from_=1, to=31,textvariable=dia, width=3)
		#s.pack(side=LEFT)

		birthdayE = Entry(self.f6, textvariable=dia, width=3)
		birthdayE.pack(side=LEFT)

		self.birthdayL3 = Label(self.f6, text='Mes:')
		self.birthdayL3.pack(padx=5,side=LEFT)

		birthdayCbx = Combobox(self.f6, textvariable=mes, values=meses, width=10)
		birthdayCbx.set('Enero')
		birthdayCbx.pack(side=LEFT)
		
		self.f7 = Frame(self.tab1)
		self.f7.pack(pady=5,fill=X)#------------------------------------

		self.mailL = Label(self.f7, text='Dir. Correspondencia:')
		self.mailL.pack(side=LEFT)
		mailE = Entry(self.f7, textvariable=envio)
		mailE.pack(side=LEFT, fill=X, expand=1)
		mailE.bind("<KeyRelease>", caps)

		self.mobileL = Label(self.f7, text='Celular:')
		self.mobileL.pack(side=LEFT)
		mobileE = Entry(self.f7, textvariable=celular, width=10)
		mobileE.pack(side=LEFT, fill=X, expand=1)
		
		self.f8 = Frame(self.tab1)
		self.f8.pack(pady=5,fill=X)#------------------------------------

		self.personL = Label(self.f8, text='Tipo Persona:')
		self.personL.pack(side=LEFT)
		
		personR1 = Radiobutton(self.f8, text="Natural", variable=tipopersona, value=1)
		personR1.pack(padx=20,side=LEFT)
		
		personR2 = Radiobutton (self.f8, text="Jurídica", variable=tipopersona, value=2)
		personR2.pack(padx=20,side=LEFT)

		self.comisionL = Label(self.f8, text='$ Comisión:')
		self.comisionL.pack(side=LEFT)
		
		comisionE = Entry(self.f8, textvariable=comision, width=5)
		comisionE.pack(side=LEFT)
		
		self.f = Frame(self.tab1)
		self.f.pack(pady=5,fill=X)#------------------------------------

		Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente)
		Ch1.pack(side=LEFT)
		
		Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva)
		Ch2.pack(side=LEFT)
		
		Ch3 = Checkbutton(self.f, text="Gran Contribuyente", variable=gcontribuyente)
		Ch3.pack(side=LEFT)
		
		Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura)
		Ch4.pack(side=LEFT)
		
		Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque)
		Ch5.pack(side=LEFT)

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

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

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

		note = Text(self.f10, height=5)
		note.pack(side=LEFT, fill=X, expand=1)
		
		self.tab1.pack()
		
		#-----------------------> TAB 2
		
		self.tab2 = Frame (self.nb)
		self.tab2.pack()
		
		self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label
		self.f0.pack(fill=X, pady=10)#----------------------------------
		
		#======================= COMPLEMENTARIOS =======================
		
		self.lf = LabelFrame(self.tab2, text="Datos Representante")
		
		self.f0 = Frame(self.lf)
		self.f0.pack(fill=X, pady=5)#-------------------------------
		
		self.ccRL = Label(self.f0, text='CC:')
		self.ccRL.pack(side=LEFT)
		cc0E = Entry(self.f0, textvariable=reprecc, width=10)
		cc0E.pack(side=LEFT, fill=X, expand=1)
		
		self.nameL = Label(self.f0, text='Nombres:')
		self.nameL.pack(side=LEFT)
		name0E = Entry(self.f0, textvariable=reprenombres)
		name0E.pack(side=LEFT, fill=X, expand=1)
		name0E.bind("<KeyRelease>", caps)
		
		self.f1 = Frame(self.lf)
		self.f1.pack(fill=X, pady=5)#-------------------------------
		
		self.adressL = Label(self.f1, text='Dir. Casa:')
		self.adressL.pack(side=LEFT)
		adress0E = Entry(self.f1, textvariable=repredireccion)
		adress0E.pack(side=LEFT, fill=X, expand=1)
		adress0E.bind("<KeyRelease>", caps)

		self.phoneL = Label(self.f1, text='Tel:')
		self.phoneL.pack(side=LEFT)
		phone0E = Entry(self.f1, textvariable=repretelefono, width=20)
		phone0E.pack(side=LEFT)
		
		self.f2 = Frame(self.lf)
		self.f2.pack(fill=X, pady=5)#-------------------------------
		
		self.officeL = Label(self.f2, text='Dir. Oficina:')
		self.officeL.pack(side=LEFT)
		office0E = Entry(self.f2, textvariable=repreoficina)
		office0E.pack(side=LEFT, fill=X, expand=1)
		office0E.bind("<KeyRelease>", caps)

		self.officetelL = Label(self.f2, text='Tel:')
		self.officetelL.pack(side=LEFT)
		officetel0E = Entry(self.f2, textvariable=repretel, width=20)
		officetel0E.pack(fill=X, side=LEFT)
		
		self.f3 = Frame (self.lf)
		self.f3.pack(fill=X)#-------------------------------------------
		
		self.tbancpL = Label(self.f3, text='Banco:')
		self.tbancpL.pack(side=LEFT)
		bank0Cbx = Combobox(self.f3, textvariable=reprebanco, values=tbancos, width=12)
		bank0Cbx.set('')
		bank0Cbx.pack(side=LEFT)

		self.tbancpL = Label(self.f3, text='Tipo Cuenta:')
		self.tbancpL.pack(side=LEFT)
		tbank0Cbx = Combobox(self.f3, textvariable=repretcuenta, values=tbanktype, width=8)
		tbank0Cbx.set('')
		tbank0Cbx.pack(side=LEFT)

		self.tcuentaL = Label(self.f3, text='# Cuenta:')
		self.tcuentaL.pack(side=LEFT)
		tcuenta0E = Entry(self.f3, textvariable=reprenumcuenta)
		tcuenta0E.pack(side=LEFT, fill=X, expand=1)
		
		self.lf.pack(fill=X, ipady=5)#==================================
		
		self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label
		self.f0.pack(fill=X, pady=10)#-------------------------------
		
		#---------------------------------------------------------------
		
		self.lf1 = LabelFrame(self.tab2, text="Datos Titular 1")
		
		self.f4 = Frame(self.lf1)
		self.f4.pack(fill=X, pady=5)#-------------------------------
		
		self.ccL = Label(self.f4, text='CC:')
		self.ccL.pack(side=LEFT)
		cc1E = Entry(self.f4, textvariable=tit1cc)
		cc1E.pack(side=LEFT, fill=X, expand=1)
		
		self.nameL = Label(self.f4, text='Nombres:')
		self.nameL.pack(side=LEFT)
		name1E = Entry(self.f4, textvariable=tit1nombres)
		name1E.pack(side=LEFT, fill=X, expand=1)
		name1E.bind("<KeyRelease>", caps)
		
		self.f5 = Frame (self.lf1)
		self.f5.pack(fill=X)#-------------------------------------------
		
		self.tbancpL = Label(self.f5, text='Banco:')
		self.tbancpL.pack(side=LEFT)
		bank1Cbx = Combobox(self.f5, textvariable=tit1banco, values=tbancos, width=12)
		bank1Cbx.set('')
		bank1Cbx.pack(side=LEFT)

		self.tbancpL = Label(self.f5, text='Tipo Cuenta:')
		self.tbancpL.pack(side=LEFT)
		tbank1Cbx = Combobox(self.f5, textvariable=tit1tcuenta, values=tbanktype, width=8)
		tbank1Cbx.set('')
		tbank1Cbx.pack(side=LEFT)

		self.tcuentaL = Label(self.f5, text='# Cuenta:')
		self.tcuentaL.pack(side=LEFT)
		tcuenta1E = Entry(self.f5, textvariable=tit1numcuenta)
		tcuenta1E.pack(side=LEFT, fill=X, expand=1)
		
		self.lf1.pack(fill=X, ipady=5)#================================
		
		self.f0 = Frame(self.tab2)#Para dejar espacio entre Tab y Label
		self.f0.pack(fill=X, pady=10)#-------------------------------
		
		#---------------------------------------------------------------
		
		self.lf2 = LabelFrame(self.tab2, text="Datos Titular 2")
		
		self.f5 = Frame(self.lf2)
		self.f5.pack(fill=X, pady=5)#-------------------------------
		
		self.ccL = Label(self.f5, text='CC:')
		self.ccL.pack(side=LEFT)
		cc2E = Entry(self.f5, textvariable=tit2cc)
		cc2E.pack(side=LEFT, fill=X, expand=1)
		
		self.nameL = Label(self.f5, text='Nombres:')
		self.nameL.pack(side=LEFT)
		name2E = Entry(self.f5, textvariable=tit2nombres)
		name2E.pack(side=LEFT, fill=X, expand=1)
		name2E.bind("<KeyRelease>", caps)
		
		self.f6 = Frame (self.lf2)
		self.f6.pack(fill=X)#-------------------------------------------
		
		self.tbancpL = Label(self.f6, text='Banco:')
		self.tbancpL.pack(side=LEFT)
		bank2Cbx = Combobox(self.f6, textvariable=tit2banco, values=tbancos, width=12)
		bank2Cbx.set('')
		bank2Cbx.pack(side=LEFT)

		self.tbancpL = Label(self.f6, text='Tipo Cuenta:')
		self.tbancpL.pack(side=LEFT)
		tbank2Cbx = Combobox(self.f6, textvariable=tit2tcuenta, values=tbanktype, width=8)
		tbank2Cbx.set('')
		tbank2Cbx.pack(side=LEFT)

		self.tcuentaL = Label(self.f6, text='# Cuenta:')
		self.tcuentaL.pack(side=LEFT)
		tcuenta2E = Entry(self.f6, textvariable=tit2numcuenta)
		tcuenta2E.pack(side=LEFT, fill=X, expand=1)
		
		self.lf2.pack(fill=X, ipady=5)#================================
		
		#---------------------------------------------------------------
		
		self.nb.add (self.tab1, text="Personales")
		self.nb.add(self.tab2, text="Complementarios")
		
		self.nb.pack()
		
		#=========================== BOTONES ===========================

		self.btns = Frame(self.wrapper)
		self.btns.pack()#-------------------------------
	
		clean = Button(self.btns, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
		clean.pack(side=RIGHT)

		update = Button(self.btns, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED)
		update.pack(side=RIGHT)
		
		add = Button(self.btns, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=Agregar)
		add.pack(side=RIGHT)
		
		#========================= ASIDE ===========================
		
		self.aside = Frame(self)
		self.aside.pack(side=LEFT, fill=BOTH, expand=True)
		
		self.wrap1 = Frame(self.aside)
		self.wrap1.pack()
		
		self.viewer = Label(self.wrap1, text="LISTA DE PROPIETARIOS")
		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, bg='#d8ecf3')
		scroll.config (command=lb.yview)
		lb.pack(fill=BOTH)
		lb.bind("<Double-Button-1>", callback)
		lb.bind("<Button-3>", popup)
		#lb.bind('<Escape>', release)
		
		self.wrap2 = Frame(self.aside)
		self.wrap2.pack()
		
		self.updateBP = Button(self.wrap2, text='Cargar lista', width=20, bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista)
		self.updateBP.pack()
		
		delete = Button(self.wrap2, text='Borrar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=borrar)
		delete.pack()
		
		edit = Button(self.wrap2, text='Modificar', bg='navy', width=20, foreground='white', activebackground='red3', activeforeground='white', command=modificar)
		edit.pack()
		
		self.wrap3 = Frame(self.aside)
		self.wrap3.pack()
		
		buscador = Label(self.wrap3, text="Buscar por:")
		buscador.pack(side=LEFT)
		
		R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1)
		R1.pack(side=LEFT)
		R2 = Radiobutton (self.wrap3, text="Apellido", variable=info, value=2)
		R2.pack(side=LEFT)
		info.set(1)
		
		self.wrap4 = Frame(self.aside)
		self.wrap4.pack()
		
		E = Entry(self.wrap4, textvariable=busqueda, width=24)
		E.pack()
		E.bind("<KeyRelease>", caps)
Beispiel #26
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        #VARIABLES GLOBALES
        global cod, cc, inquilino, codinm, inmueble, nit, owner, rel, vlrenta, duracion
        global contratos, tcontrato, incremento, gfacturaIni, facturaSgte, fecha, hoy
        global notas, anexos, destinacion, servicios, conexos, tercero, nombret, fecha
        global aplicado, cc_aplicado, n_aplicado, inm_aplicado, novedad, n_nombre, n_valor
        global h, busqueda, clean, update, add

        #INSTANCIEAS DE LOS WIDGETS
        global e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, Cbx1, chkb1, chkb2, lb, cedulaE, notas

        fecha = datetime.date.today()
        hoy = "%s" % fecha  #ESTE NUESTRA LA FECHA EN FORMATO AÑO-MES-DIA (YYYY/MM/DD)
        #hoy = time.strftime("%d/%m/%y") #ESTO PARA VER FORMATO FECHA EN DIA/MES/AÑO
        #hoy = time.strftime("%y/%m/%d")
        h = hoy

        #VARIABLES
        lupa = PhotoImage(file='img/lupa.png')
        schedule = PhotoImage(file='img/calendar.gif')

        cod = IntVar()
        cc = StringVar()
        inquilino = StringVar()
        codinm = IntVar()
        inmueble = StringVar()
        nit = StringVar()
        owner = StringVar()
        rel = IntVar()

        vlrenta = DoubleVar()
        duracion = IntVar()
        contratos = ['Vivienda', 'Comercial', 'Mixta']
        tcontrato = StringVar()
        incremento = DoubleVar()
        gfacturaIni = IntVar()
        facturaSgte = IntVar()
        fecha = StringVar()

        notas = StringVar()
        anexos = StringVar()
        destinacion = StringVar()
        servicios = StringVar()
        conexos = StringVar()

        tercero = StringVar()
        nombret = StringVar()

        aplicado = IntVar()
        cc_aplicado = StringVar()
        n_aplicado = StringVar()
        inm_aplicado = StringVar()
        novedad = StringVar()
        n_nombre = StringVar()
        n_valor = DoubleVar()

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

        #WIDGETS

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

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

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

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

        #================ NOTEBOOK =============>

        self.nb = Notebook(self.wrapper)

        #-----------------------> TAB 1

        self.tab1 = Frame(self.nb)

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

        l1 = Label(self.f0, text='Código:')
        l1.pack(side=LEFT)

        e1 = Entry(self.f0, textvariable=cod, width=10)
        e1.pack(side=LEFT)

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

        l2 = Label(self.f1, text='Arrendatario:')
        l2.pack(side=LEFT, fill=X)

        e2 = Entry(self.f1, textvariable=cc, width=15)
        e2.pack(side=LEFT)
        e2.bind('<Return>', buscarA)

        b1 = Button(self.f1, image=lupa, command=topArrendatario)
        b1.image = lupa
        b1.pack(side=LEFT)

        e3 = Entry(self.f1, textvariable=inquilino, state=DISABLED)
        e3.pack(side=LEFT, fill=X, expand=1)

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

        l3 = Label(self.f2, text='Inmueble:')
        l3.pack(side=LEFT)

        e4 = Entry(self.f2, textvariable=codinm, width=10)
        e4.pack(side=LEFT)
        e4.bind('<Return>', buscarR)

        b2 = Button(self.f2, image=lupa, command=topRelacion)
        b2.pack(side=LEFT)

        e5 = Entry(self.f2, textvariable=inmueble, state=DISABLED)
        e5.pack(side=LEFT, fill=X, expand=1)

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

        l4 = Label(self.f3, text='Propietario:')
        l4.pack(side=LEFT)

        e6 = Entry(self.f3, width=15, textvariable=nit, state=DISABLED)
        e6.pack(side=LEFT)
        e7 = Entry(self.f3, width=5, textvariable=owner, state=DISABLED)
        e7.pack(side=LEFT, fill=X, expand=1)

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

        self.arriendo = Label(self.f4, text='Arriendo $:')
        self.arriendo.pack(side=LEFT)
        e8 = Entry(self.f4, textvariable=vlrenta, state=DISABLED, width=20)
        e8.pack(side=LEFT)

        self.duracion = Label(self.f4, text='Duración Contrato:')
        self.duracion.pack(side=LEFT)
        e9 = Entry(self.f4, textvariable=duracion, width=5)
        e9.pack(side=LEFT)

        self.meses = Label(self.f4, text='Meses')
        self.meses.pack(side=LEFT)

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

        self.tcontrato = Label(self.f5, text='Tipo Contrato:')
        self.tcontrato.pack(side=LEFT)

        Cbx1 = Combobox(self.f5,
                        textvariable=tcontrato,
                        values=contratos,
                        width=10)
        Cbx1.set('')
        Cbx1.pack(side=LEFT)

        self.incremento = Label(self.f5, text='Incremento:')
        self.incremento.pack(side=LEFT)
        e10 = Entry(self.f5, textvariable=incremento, width=5)
        e10.pack(side=LEFT)

        chkb1 = Checkbutton(self.f5,
                            text="General factura\n inicial",
                            variable=gfacturaIni)
        chkb1.pack(side=LEFT)
        chkb2 = Checkbutton(self.f5,
                            text="Facturar príodo\n siguiente",
                            variable=facturaSgte)
        chkb2.pack(side=LEFT)

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

        btime = Button(self.f6, image=schedule, command=calendario)
        btime.image = schedule
        btime.pack(side=RIGHT)

        etime = Entry(self.f6, textvariable=fecha, width=10)
        fecha.set(hoy)
        etime.pack(side=RIGHT)

        #ltime = Label(self.f6, text=hoy, font="bold", foreground='red')
        #ltime.pack(side=RIGHT)

        self.fi = Label(self.f6, text='Fecha Inicio: ')
        self.fi.pack(side=RIGHT)

        self.tab1.pack()

        #-----------------------> TAB 2

        self.tab2 = Frame(self.nb)
        self.tab2.pack()

        self.f7 = Frame(self.tab2)  #-------------------------------------
        self.f7.pack(fill=X, pady=10)

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

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

        self.destino = Label(self.f8, text='Destinación:')
        self.destino.pack(side=LEFT)
        self.destinoE = Entry(self.f8, textvariable=destinacion, width=5)
        self.destinoE.pack(side=LEFT, fill=X, expand=1)

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

        self.servicios = Label(self.f9, text='Servicios adicionales:')
        self.servicios.pack(side=LEFT)
        self.serviciosE = Entry(self.f9, textvariable=servicios, width=5)
        self.serviciosE.pack(side=LEFT, fill=X, expand=1)

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

        self.conexos = Label(self.f10, text='Conexos:')
        self.conexos.pack(side=LEFT)
        self.conexosE = Entry(self.f10, textvariable=conexos, width=5)
        self.conexosE.pack(side=LEFT, fill=X, expand=1)

        #-----------------------> TAB 3

        self.tab3 = Frame(self.nb)
        self.tab3.pack()

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

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

        cedulaE = Entry(self.f11, textvariable=tercero, width=15)
        cedulaE.pack(side=LEFT)
        cedulaE.bind('<Return>', buscarT)

        b4 = Button(self.f11, image=lupa, command=topTercero)
        b4.image = lupa
        b4.pack(side=LEFT)

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

        self.tercero = Label(self.f12, text='Nombre: ')
        self.tercero.pack(side=LEFT)

        self.terceroE = Entry(self.f12,
                              textvariable=nombret,
                              width=5,
                              state=DISABLED)
        self.terceroE.pack(side=LEFT, fill=X, expand=1)

        #-----------------------> TAB 4

        self.tab4 = Frame(self.nb)
        self.tab4.pack()

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

        l = Label(self.f13, text='Aplicar a: ')
        l.pack(side=LEFT)

        Ch = Checkbutton(self.f13, text="Propietario", variable=aplicado)
        Ch.pack(side=LEFT)

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

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

        e13 = Entry(self.f14, textvariable=cc_aplicado, width=15)
        e13.pack(side=LEFT)

        b13 = Button(self.f14, image=lupa, command=None)
        b13.image = lupa
        b13.pack(side=LEFT)

        e13 = Entry(self.f14, textvariable=n_aplicado, state=DISABLED)
        e13.pack(side=LEFT, fill=X, expand=1)

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

        l14 = Label(self.f15, text='Cod.Inmueble:')
        l14.pack(side=LEFT)

        e14 = Entry(self.f15,
                    textvariable=inm_aplicado,
                    width=5,
                    state=DISABLED)
        e14.pack(side=LEFT, fill=X, expand=1)

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

        l16 = Label(self.f16, text='Novedad:')
        l16.pack(side=LEFT, fill=X)

        e16 = Entry(self.f16, textvariable=novedad, width=15)
        e16.pack(side=LEFT)

        b16 = Button(self.f16, image=lupa, command=None)
        b16.image = lupa
        b16.pack(side=LEFT)

        e16 = Entry(self.f16, textvariable=n_nombre, state=DISABLED)
        e16.pack(side=LEFT, fill=X, expand=1)

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

        l17 = Label(self.f17, text='Vlr Novedad:')
        l17.pack(side=LEFT, fill=X)

        e17 = Entry(self.f17, textvariable=n_valor, width=15)
        e17.pack(side=LEFT)

        #---------------------------------------------------------------

        self.nb.add(self.tab1, text="General")
        self.nb.add(self.tab2, text="Anexos")
        self.nb.add(self.tab3, text="Tercero")
        self.nb.add(self.tab4, text="Gasto fijo")

        self.nb.pack()

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

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

        update = Button(self.fBtn,
                        text='Actualizar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=actualizar,
                        state=DISABLED)
        update.pack(side=RIGHT)

        add = Button(self.fBtn,
                     text='Agregar',
                     bg='navy',
                     foreground='white',
                     activebackground='red3',
                     activeforeground='white',
                     command=agregar)
        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 CONTRATOS")
        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)
        lb.bind("<Double-Button-1>", callback)

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

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

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

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

        buscador = Label(self.wrap2, text="Buscar por CC:")
        buscador.pack()
        E = Entry(self.wrap2, textvariable=busqueda, width=24)
        E.pack()
class Application(Frame):
    def __init__(self, master=None, config=config):
        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self)))
        self.display_connections = True

        Frame.__init__(self, master)
        self.pack(fill=BOTH, expand=True)
        Style().configure("TFrame", background="#444")

        self.paint_tile = 1
        self.init_ui()

    def init_ui(self):
        self.connections = {}
        self.button_frame = Frame(self)
        self.button_frame.grid(row=0, column=0, columnspan=2)
        self.map_frame = Frame(self)
        self.map_frame.grid(row=1, column=0, padx=5, pady=5, sticky=N + S + E + W)
        self.picker_frame = Frame(self)
        self.picker_frame.grid(row=1, column=1)

        self.button_new = Button(self.button_frame)
        self.button_new["text"] = "New"
        self.button_new["command"] = self.new_map
        self.button_new.grid(row=0, column=0, padx=2)

        self.menubar = Menu(self)

        menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="File", menu=menu)
        menu.add_command(label="New")
        menu.add_command(label="Open")
        menu.add_command(label="Save")

        self.open = Button(self.button_frame)
        self.open["text"] = "Open"
        self.open["command"] = self.open_map
        self.open.grid(row=0, column=1, padx=2)

        self.save = Button(self.button_frame)
        self.save["text"] = "Save"
        self.save["command"] = self.save_map
        self.save.grid(row=0, column=2, padx=2)

        self.get_map_list()
        self.map_list.grid(row=0, column=3, padx=2)

    def get_map_list(self):
        self.available_maps = sorted(m for m in get_available_maps(config=self.config))
        self.map_list = Combobox(self.button_frame, height=24, width=24, values=self.available_maps)
        if len(self.available_maps):
            self.map_list.set(self.available_maps[0])

    def new_map(self):
        self.map_name = None
        self.init_map()
        self.map.map.blockdata = bytearray([self.paint_tile] * 20 * 20)
        self.map.map.width = 20
        self.map.map.height = 20
        self.draw_map()
        self.init_picker()

    def open_map(self):
        self.map_name = self.map_list.get()
        self.init_map()
        self.draw_map()
        self.init_picker()

    def save_map(self):
        if hasattr(self, "map"):
            if self.map.map.blk_path:
                initial = self.map.map.blk_path
            else:
                initial = self.config.path
            filename = tkFileDialog.asksaveasfilename(initialfile=initial)
            if filename:
                with open(filename, "wb") as save:
                    save.write(self.map.map.blockdata)
                self.log.info("blockdata saved as {}".format(filename))
        else:
            self.log.info("nothing to save")

    def init_map(self):
        if hasattr(self, "map"):
            self.map.kill_canvas()
        self.map = MapRenderer(self.config, parent=self.map_frame, name=self.map_name)
        self.init_map_connections()

    def draw_map(self):
        self.map.init_canvas(self.map_frame)
        self.map.canvas.pack()  # .grid(row=1,column=1)
        self.map.draw()
        self.map.canvas.bind("<Button-1>", self.paint)
        self.map.canvas.bind("<B1-Motion>", self.paint)

    def init_picker(self):
        """This should really be its own class."""
        self.current_tile = MapRenderer(
            self.config, parent=self.button_frame, tileset=Tileset(id=self.map.map.tileset.id)
        )
        self.current_tile.map.blockdata = [self.paint_tile]
        self.current_tile.map.width = 1
        self.current_tile.map.height = 1
        self.current_tile.init_canvas()
        self.current_tile.draw()
        self.current_tile.canvas.grid(row=0, column=4, padx=4)

        if hasattr(self, "picker"):
            self.picker.kill_canvas()
        self.picker = MapRenderer(self.config, parent=self, tileset=Tileset(id=self.map.map.tileset.id))
        self.picker.map.blockdata = range(len(self.picker.map.tileset.blocks))
        self.picker.map.width = 4
        self.picker.map.height = len(self.picker.map.blockdata) / self.picker.map.width
        self.picker.init_canvas(self.picker_frame)

        if hasattr(self.picker_frame, "vbar"):
            self.picker_frame.vbar.destroy()
        self.picker_frame.vbar = Scrollbar(self.picker_frame, orient=VERTICAL)
        self.picker_frame.vbar.pack(side=RIGHT, fill=Y)
        self.picker_frame.vbar.config(command=self.picker.canvas.yview)

        self.picker.canvas.config(scrollregion=(0, 0, self.picker.canvas_width, self.picker.canvas_height))
        self.map_frame.update()

        # overwriting a property is probably a bad idea
        self.picker.canvas_height = self.map_frame.winfo_height()

        self.picker.canvas.config(yscrollcommand=self.picker_frame.vbar.set)
        self.picker.canvas.pack(side=LEFT, expand=True)

        self.picker.canvas.bind("<4>", lambda event: self.scroll_picker(event))
        self.picker.canvas.bind("<5>", lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind("<4>", lambda event: self.scroll_picker(event))
        self.picker_frame.vbar.bind("<5>", lambda event: self.scroll_picker(event))

        self.picker.draw()
        self.picker.canvas.bind("<Button-1>", self.pick_block)

    def scroll_picker(self, event):
        if event.num == 4:
            self.picker.canvas.yview("scroll", -1, "units")
        elif event.num == 5:
            self.picker.canvas.yview("scroll", 1, "units")

    def pick_block(self, event):
        block_x = int(self.picker.canvas.canvasx(event.x)) / (
            self.picker.map.tileset.block_width * self.picker.map.tileset.tile_width
        )
        block_y = int(self.picker.canvas.canvasy(event.y)) / (
            self.picker.map.tileset.block_height * self.picker.map.tileset.tile_height
        )
        i = block_y * self.picker.map.width + block_x
        self.paint_tile = self.picker.map.blockdata[i]

        self.current_tile.map.blockdata = [self.paint_tile]
        self.current_tile.draw()

    def paint(self, event):
        block_x = event.x / (self.map.map.tileset.block_width * self.map.map.tileset.tile_width)
        block_y = event.y / (self.map.map.tileset.block_height * self.map.map.tileset.tile_height)
        i = block_y * self.map.map.width + block_x
        if 0 <= i < len(self.map.map.blockdata):
            self.map.map.blockdata[i] = self.paint_tile
            self.map.draw_block(block_x, block_y)

    def init_map_connections(self):
        if not self.display_connections:
            return

        for direction in self.map.map.connections.keys():

            if direction in self.connections.keys():
                if hasattr(self.connections[direction], "canvas"):
                    self.connections[direction].kill_canvas()

            if self.map.map.connections[direction] == {}:
                self.connections[direction] = {}
                continue

            self.connections[direction] = MapRenderer(
                self.config, parent=self, name=self.map.map.connections[direction]["map_name"]
            )

            attrs = self.map.map.connections[direction]
            if direction in ["north", "south"]:
                if direction == "north":
                    x1 = 0
                    if self.config.version == "red":
                        y1 = eval(attrs["other_height"], self.config.constants) - 3
                    elif self.config.version == "crystal":
                        y1 = eval(attrs["map"] + "_HEIGHT", self.config.constants) - 3
                else:  # south
                    x1 = 0
                    y1 = 0
                x2 = x1 + eval(attrs["strip_length"], self.config.constants)
                y2 = y1 + 3
            else:
                if direction == "east":
                    x1 = 0
                    y1 = 0
                else:  # west
                    x1 = -3
                    y1 = 1
                x2 = x1 + 3
                y2 = y1 + eval(attrs["strip_length"], self.config.constants)

            self.connections[direction].init_canvas(self.map_frame)
            self.connections[direction].canvas.pack(
                side={"north": TOP, "south": BOTTOM, "west": LEFT, "east": RIGHT}[direction]
            )
            self.connections[direction].map.crop(x1, y1, x2, y2)
            self.connections[direction].draw()
Beispiel #28
0
class MainFrame(Frame):
    def __init__(self, parent, stdoutq):
        Frame.__init__(self, parent)

        self.parent = parent
        self.width = 850
        self.height = 650
        self.title = menotexport.__version__
        self.stdoutq = stdoutq

        self.initUI()

        self.hasdb = False
        self.hasout = False
        self.hasaction = False
        self.exit = False

        self.path_frame = self.addPathFrame()
        self.action_frame = self.addActionFrame()
        self.message_frame = self.addMessageFrame()
        self.printStr()

        self.stateq = Queue.Queue()
        #self.workproc=Pool(1)

    def centerWindow(self):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - self.width) / 2
        y = (sh - self.height) / 2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))

    def initUI(self):
        self.parent.title(self.title)
        self.style = Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH, expand=True)
        self.centerWindow()

    def printStr(self):
        while self.stdoutq.qsize() and self.exit == False:
            try:
                msg = self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END, msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100, self.printStr)

    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1 or self.isbib.get()==1:
            self.hasaction = True
        else:
            self.hasaction = False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('# <Menotexport>: Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)

    def addPathFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.X, expand=0, side=tk.TOP, padx=8, pady=5)

        frame.columnconfigure(1, weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry = tk.Entry(frame)
        self.db_entry.grid(row=0, column=1, sticky=tk.W + tk.E, padx=8)

        self.db_button = tk.Button(frame, text='Open', command=self.openFile)
        self.db_button.grid(row=0, column=2, padx=8, sticky=tk.E)

        hint = '''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry = tk.Entry(frame)
        self.out_entry.grid(row=2, column=1, sticky=tk.W + tk.E, padx=8)
        self.out_button = tk.Button(frame, text='Choose', command=self.openDir)
        self.out_button.grid(row=2, column=2, padx=8, sticky=tk.E)

    def openDir(self):
        self.out_entry.delete(0, tk.END)
        dirname = askdirectory()
        self.out_entry.insert(tk.END, dirname)
        if len(dirname) > 0:
            print('# <Menotexport>: Output folder: %s' % dirname)
            self.hasout = True
            self.checkReady()

    def openFile(self):
        self.db_entry.delete(0, tk.END)
        ftypes = [('sqlite files', '*.sqlite'), ('ALL files', '*')]
        initialdir = '~/.local/share/data/Mendeley Ltd./Mendeley Desktop'
        initialdir = os.path.expanduser(initialdir)
        if os.path.isdir(initialdir):
            filename = askopenfilename(filetypes=ftypes, initialdir=initialdir)
        else:
            filename = askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END, filename)
        if len(filename) > 0:
            print('# <Menotexport>: Database file: %s' % filename)
            self.probeFolders()

    def probeFolders(self):
        dbfile = self.db_entry.get()
        try:
            db = sqlite3.connect(dbfile)
            self.menfolderlist = menotexport.getFolderList(db,
                                                           None)  #(id, name)
            self.foldernames = ['All'] + [ii[1] for ii in self.menfolderlist
                                          ]  #names to display
            self.foldersmenu['values'] = tuple(self.foldernames)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb = True
            self.checkReady()

        except Exception as e:
            print(
                '# <Menotexport>: Failed to recoganize the given database file.'
            )
            print(e)

    def addActionFrame(self):

        frame = Frame(self, relief=tk.RAISED, borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label = tk.Label(frame, text='Actions:', bg='#bbb')
        label.grid(row=0, column=0, sticky=tk.W, padx=8)

        #---------------Action checkbuttons---------------
        self.isexport = tk.IntVar()
        self.ishighlight = tk.IntVar()
        self.isnote = tk.IntVar()
        self.isbib = tk.IntVar()
        self.isris = tk.IntVar()
        self.isseparate = tk.IntVar()
        self.iszotero = tk.IntVar()
        self.iscustomtemp = tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_bib=tk.Checkbutton(frame,\
                text='Export .bib',\
                variable=self.isbib,command=self.doBib)

        self.check_ris=tk.Checkbutton(frame,\
                text='Export .ris',\
                variable=self.isris,command=self.doRis)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        self.check_iszotero=tk.Checkbutton(frame,\
                text='For import to Zotero',\
                variable=self.iszotero,command=self.doIszotero,\
                state=tk.DISABLED)

        self.check_custom_template=tk.Checkbutton(frame,\
                text='Use custom template (experimental)',\
                variable=self.iscustomtemp,command=self.doCustomTemp,\
                state=tk.DISABLED)

        frame.columnconfigure(0, weight=1)

        self.check_export.grid(row=1, column=1, padx=8, sticky=tk.W)
        self.check_highlight.grid(row=1, column=2, padx=8, sticky=tk.W)
        self.check_note.grid(row=1, column=3, padx=8, sticky=tk.W)
        self.check_bib.grid(row=2, column=1, padx=8, sticky=tk.W)
        self.check_ris.grid(row=2, column=2, padx=8, sticky=tk.W)
        self.check_separate.grid(row=2, column=3, padx=8, sticky=tk.W)
        self.check_iszotero.grid(row=3, column=1, padx=8, sticky=tk.W)
        self.check_custom_template.grid(row=3, column=2, padx=8, sticky=tk.W)

        #---------------------2nd row---------------------
        subframe = Frame(frame)
        subframe.grid(row=4,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder = tk.StringVar()
        self.menfolderlist = [
            'All',
        ]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>', self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT, padx=8)

        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT, padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''

        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT, pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT, padx=8)

    def setfolder(self, x):
        self.foldersmenu.selection_clear()
        self.menfolder = self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder == 'All':
            print('# <Menotexport>: Work on all folders.')
        else:
            print('# <Menotexport>: Select Mendeley folder: ' +
                  str(self.menfolder))

    def doExport(self):
        if self.isexport.get() == 1:
            print('# <Menotexport>: Export annotated PDFs.')
        else:
            print('# <Menotexport>: Dont export annotated PDFs.')

        self.checkReady()

    def doHighlight(self):
        if self.ishighlight.get() == 1:
            print('# <Menotexport>: Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract highlighted texts.')
            if self.isnote.get() == 0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get() == 1:
            print('# <Menotexport>: Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
            self.check_custom_template.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont extract notes.')
            self.check_separate.state = tk.DISABLED
            if self.ishighlight.get() == 0:
                self.check_separate.configure(state=tk.DISABLED)
                self.check_custom_template.configure(state=tk.DISABLED)
        self.checkReady()
        self.checkReady()

    def doBib(self):
        if self.isbib.get() == 1:
            print('# <Menotexport>: Export to .bib file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .bib file.')
            if self.isris.get() == 0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doRis(self):
        if self.isris.get() == 1:
            print('# <Menotexport>: Export to .ris file.')
            self.check_iszotero.configure(state=tk.NORMAL)
        else:
            print('# <Menotexport>: Dont export .ris file.')
            if self.isbib.get() == 0:
                self.check_iszotero.configure(state=tk.DISABLED)
        self.checkReady()

    def doSeparate(self):
        if self.isseparate.get() == 1:
            print('# <Menotexport>: Save annotations separately.')
        else:
            print('# <Menotexport>: Save all annotations to single file.')

    def doIszotero(self):
        if self.iszotero.get() == 1:
            print(
                '# <Menotexport>: Save .bib/.ris file in Zotero preferred format.'
            )
        else:
            print('# <Menotexport>: Save .bib/.ris file to default format.')

    def doCustomTemp(self):
        if self.iscustomtemp.get() == 1:
            print(
                '# <Menotexport>: Use custom template for exported annotations.'
            )
        else:
            print(
                '# <Menotexport>: Use default template for exported annotations.'
            )

    def showHelp(self):
        helpstr = '''
%s\n\n
- Export PDFs: Bulk export PDFs.\n
- Extract highlights: Extract highlighted texts and output to txt files.\n
- Extract notes: Extract notes and output to txt files.\n
- Export .bib: Export meta-data and annotations to .bib files.\n
- Export .ris: Export meta-data and annotations to .ris files.\n
- For import to Zotero: Exported .bib and/or .ris files have suitable format to import to Zotero.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- Use custom annotation template: Use a custom template to format the exported annotations.
  See annotation_template.py for details.
- See README.md for more info.\n
''' % self.title

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())

    def start(self):
        dbfile = self.db_entry.get()
        outdir = self.out_entry.get()
        self.menfolder = self.foldersmenu.get()

        # get (folderid, folder) for folder
        for ii in self.menfolderlist:
            if ii[1] == self.menfolder:
                folder_sel = [ii[0], ii[1].split('/')[-1]]

        action = []
        if self.isexport.get() == 1:
            action.append('p')
        if self.ishighlight.get() == 1:
            action.append('m')
        if self.isnote.get() == 1:
            action.append('n')
        if self.isbib.get() == 1:
            action.append('b')
        if self.isris.get() == 1:
            action.append('r')
        if self.isseparate.get() == 1:
            separate = True
        else:
            separate = False
        if self.iszotero.get() == 1:
            iszotero = True
        else:
            iszotero = False
        if self.iscustomtemp.get() == 1:
            action.append('t')

        if 'p' in action or 'm' in action or 'n' in action or 'b' in action or 'r' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_bib.configure(state=tk.DISABLED)
            self.check_ris.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
            self.check_iszotero.configure(state=tk.DISABLED)
            self.check_custom_template.configure(state=tk.DISABLED)
            self.messagelabel.configure(text='Message (working...)')

            folder = None if self.menfolder == 'All' else folder_sel

            args = [dbfile, outdir, action, folder, separate, iszotero, True]

            self.workthread = WorkThread('work', False, self.stateq)
            self.workthread.deamon = True

            self.workthread.args = args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''

    def reset(self):
        while self.stateq.qsize() and self.exit == False:
            try:
                msg = self.stateq.get()
                if msg == 'done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_bib.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.check_iszotero.configure(state=tk.NORMAL)
                    self.check_custom_template.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100, self.reset)

    def stop(self):
        #self.workthread.stop()
        pass

    def addMessageFrame(self):
        frame = Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel = tk.Label(frame, text='Message', bg='#bbb')
        self.messagelabel.pack(side=tk.TOP, fill=tk.X)

        self.text = tk.Text(frame)
        self.text.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.text.height = 10

        scrollbar = tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #29
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 ===========================
		"""
Beispiel #30
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=750
        self.height=450
        self.title=ximaexport.__version__
        self.stdoutq=stdoutq
        
        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()


    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)



    def checkReady(self):

        if self.hasdb and self.hasout:
            self.start_button.configure(state=tk.NORMAL)
            #print('XimaExport Ready.')
            printch('XimaExport 就绪.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text=dgbk('打开'),command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text=dgbk('选择'),command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            #print('Output folder: %s' %dirname)
            printch('输出到文件夹:')
	    print('   '+dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALL files','*')]
        filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            #print('Database file: %s' %filename)
            printch('数据文件:')
	    print('   '+filename)
            self.probeAlbums()


    def probeAlbums(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            df=ximaexport.getData(db)
            self.albumlist=ximaexport.getAlbumList(df,None)   #(id, name)
            self.albumnames=['All']+[ii[1] for ii in self.albumlist] #names to display
            self.albummenu['values']=tuple(self.albumnames)
            self.albummenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            #print('Failed to recoganize the given database file.') 
            printch('无法识别sqlite数据文件.') 
            print(e)



    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        #label=tk.Label(frame,text='Actions:',bg='#bbb')
        #label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        frame.columnconfigure(0,weight=1)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=1,column=0,columnspan=6,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Album options-------------------
        albumlabel=tk.Label(subframe,text=dgbk('专辑:'),\
                bg='#bbb')
        albumlabel.pack(side=tk.LEFT, padx=8)

        self.album=tk.StringVar()
        self.albumnames=['All',]
        self.albummenu=Combobox(subframe,textvariable=\
                self.album,values=self.albumnames,state='readonly')
        self.albummenu.current(0)
        self.albummenu.bind('<<ComboboxSelected>>',self.setAlbum)
        self.albummenu.pack(side=tk.LEFT,padx=8)
        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text=dgbk('退出'),\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text=dgbk('开始'),\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------
        self.help_button=tk.Button(subframe,text=dgbk('帮助'),\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)





    def setAlbum(self,x):
	import json
        self.albummenu.selection_clear()
        self.album=self.albummenu.get()
        self.albummenu.set(self.album)
        if self.album=='All':
            #print('Work on all albums.')
            printch('导出所有专辑.')
        else:
            #print('Select album: '+self.album)
            printch('导出所选专辑:')
	    print('   '+self.album)





    def showHelp(self):
        helpstr=dgbk('''\n\n
导出喜马拉雅下载音频,并自动按专辑归档、重命名:\n
1. 找到手机/pad中的喜马拉雅数据文件夹:\n
    (1)苹果用户:链接电脑itunes,在app一栏中找到“喜马拉雅”,单击,右侧会出现“喜马拉雅”的数据文件。选择“iDoc”,并导出到电脑。\n
    (2)安卓用户:链接电脑后,拷贝出ting文件夹。\n
2. 运行ximaexport-gui.exe。\n
    在 “ting.sqlite文件”一栏,选择步骤1中拷贝出的文件夹里的 ting.sqlite. 文件。\n
    在 “导出到文件夹”一栏,选择音频存储位置。\n
    在 “专辑”下拉菜单,选择要导出的专辑。若全部导出选择“All”。\n
    点击“开始”开始处理。
''')

        tkMessageBox.showinfo(title='Help', message=helpstr)
        #print(self.menfolder.get())



    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        self.album=self.albummenu.get()

        self.out_button.configure(state=tk.DISABLED)
        self.start_button.configure(state=tk.DISABLED)
        self.help_button.configure(state=tk.DISABLED)
        self.albummenu.configure(state=tk.DISABLED)
        self.messagelabel.configure(text=dgbk('信息 (处理中...)'))

        album=None if self.album=='All' else self.album

        args=[dbfile,outdir,album,True]

        self.workthread=WorkThread('work',False,self.stateq)
        self.workthread.deamon=True

        self.workthread.args=args
        self.workthread.start()
        self.reset()


    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.albummenu.configure(state='readonly')
                    self.messagelabel.configure(text=dgbk('消息'))
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text=dgbk('消息'),bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
class MainWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title(mainWindowTitle)
        self.resizable(width=0, height=0)
        self.__setStyles()
        self.__initializeComponents()
        self.__dataController = DataController();
        self.mainloop()
            
    def __initializeComponents(self):
        self.imageCanvas = Canvas(master=self, width=imageCanvasWidth,
                                  height=windowElementsHeight, bg="white")
        self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0),
                              pady=windowPadding, fill=BOTH)
        
        self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth,
                                  height=windowElementsHeight)
        self.buttonsFrame.propagate(0)
        self.loadFileButton = Button(master=self.buttonsFrame,
                                     text=loadFileButtonText, command=self.loadFileButtonClick)
        self.loadFileButton.pack(fill=X, pady=buttonsPadding);
        
        self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText)
        self.colorByLabel.pack(fill=X)
        self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED,
                                        values=colorByComboboxValues)
        self.colorByCombobox.set(colorByComboboxValues[0])
        self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange)
        self.colorByCombobox.pack(fill=X, pady=buttonsPadding)
        self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText)
        self.rejectedValuesPercentLabel.pack(fill=X)
        self.rejectedValuesPercentEntry = Entry(self.buttonsFrame)
        self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent)
        self.rejectedValuesPercentEntry.config(state=DISABLED)
        self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding)        
        
        self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText)
        self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText)
        self.colorsTableLengthLabel.pack(fill=X)
        self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableLengthEntry.insert(0, defaultColorsTableLength)
        self.colorsTableLengthEntry.config(state=DISABLED)
        self.colorsTableLengthEntry.pack(fill=X)
        self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText)
        self.scaleTypeLabel.pack(fill=X)
        self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED,
                                          values=scaleTypesComboboxValues)
        self.scaleTypeCombobox.set(scaleTypesComboboxValues[0])
        self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange)
        self.scaleTypeCombobox.pack(fill=X)
        self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText)
        self.colorsTableMinLabel.pack(fill=X)
        self.colorsTableMinEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMinEntry.insert(0, defaultColorsTableMin)
        self.colorsTableMinEntry.config(state=DISABLED)
        self.colorsTableMinEntry.pack(fill=X)
        self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText)
        self.colorsTableMaxLabel.pack(fill=X)
        self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMaxEntry.insert(0, defaultColorsTableMax)
        self.colorsTableMaxEntry.config(state=DISABLED)
        self.colorsTableMaxEntry.pack(fill=X)
        self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding)
        
        self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText,
                                   state=DISABLED, command=self.__redrawButtonClick)
        self.redrawButton.pack(fill=X, pady=buttonsPadding)
        self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH)
        
    def __setStyles(self):
        Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont)
    
    def loadFileButtonClick(self):
        fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')])
        if (fileName):
            if (not self.__getInputParams()):
                self.__showInvalidInputMessage()
                return
            
            self.lastFileName = fileName;
            self.title(mainWindowTitle + " " + fileName)
            self.__draw(fileName)
            tkMessageBox.showinfo(measureDialogTitle, 
                                  measureDialogText + str(self.__dataController.getMeasure(fileName)))
            
            self.redrawButton.config(state=NORMAL)
            self.colorByCombobox.config(state="readonly")
            self.colorsTableLengthEntry.config(state=NORMAL)
            self.scaleTypeCombobox.config(state="readonly")
            
    def __redrawButtonClick(self):
        if (not self.__getInputParams()):
            self.__showInvalidInputMessage()
            return
        
        self.__draw(self.lastFileName)

    def __scaleTypeComboboxChange(self, event):
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            self.colorsTableMinEntry.config(state=DISABLED)
            self.colorsTableMaxEntry.config(state=DISABLED)
        else:
            self.colorsTableMinEntry.config(state=NORMAL)
            self.colorsTableMaxEntry.config(state=NORMAL)
        
    def __colorByComboboxChange(self, event):
        if (self.colorByCombobox.get() == colorByNoneOption):
            self.rejectedValuesPercentEntry.config(state=DISABLED)
        else:
            self.rejectedValuesPercentEntry.config(state=NORMAL)
        
    def __draw(self, fileName):
        self.imageCanvas.delete(ALL)

        dataForDrawing = self.__dataController.getDataForDrawing(
            fileName, self.colorByCombobox.get(), self.colorsTableLength,
            self.scaleTypeCombobox.get(), self.colorsTableMinValue,
            self.colorsTableMaxValue, self.rejectedValuesPercent)
        
        for package in dataForDrawing:
            x = package[0];
            y = package[1];
            color = package[2];
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color)
            
    def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv):   
        allSpeeds = self.__getAllSpeeds(dataPackages)
        minSpeed = min(allSpeeds)
        maxSpeed = max(allSpeeds)
        
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            colorsTableMinValue = minSpeed
            colorsTableMaxValue = maxSpeed
        else:
            colorsTableMinValue = self.colorsTableMinValue
            colorsTableMaxValue = self.colorsTableMaxValue
        
        i = 0
        for package in dataPackages:
            x = (package[dataXNumber] - minX) * ratio
            y = (package[dataYNumber] - minY) * ratio
            
            color = hsv.getColorByValue(colorsTableMinValue,
                                        colorsTableMaxValue,
                                        allSpeeds[i])
                
            tk_rgb = "#%02x%02x%02x" % color
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb)
            i += 1
            
    def __showInvalidInputMessage(self):
        tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText)
    
    def __getInputParams(self):
        try:
            self.colorsTableLength = int(self.colorsTableLengthEntry.get())
            self.colorsTableMinValue = float(self.colorsTableMinEntry.get())
            self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get())
            self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get())
        
            if (self.colorsTableLength < 1 or
                self.colorsTableMinValue >= self.colorsTableMaxValue or
                self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100):
                raise
            return True
        except:
            return False
Beispiel #32
0
class MainFrame(Frame):
    def __init__(self,parent,stdoutq):
        Frame.__init__(self,parent)

        self.parent=parent
        self.width=700
        self.height=400
        self.title='Menotexport v1.0'
        self.stdoutq=stdoutq

        self.initUI()

        self.hasdb=False
        self.hasout=False
        self.hasaction=False
        self.exit=False

        self.path_frame=self.addPathFrame()
        self.action_frame=self.addActionFrame()
        self.message_frame=self.addMessageFrame()
        self.printStr()

        self.stateq=Queue.Queue()
        #self.workproc=Pool(1)




    def centerWindow(self):
        sw=self.parent.winfo_screenwidth()
        sh=self.parent.winfo_screenheight()
        x=(sw-self.width)/2
        y=(sh-self.height)/2
        self.parent.geometry('%dx%d+%d+%d' \
                %(self.width,self.height,x,y))


    def initUI(self):
        self.parent.title(self.title)
        self.style=Style()
        #Choose from default, clam, alt, classic
        self.style.theme_use('alt')
        self.pack(fill=tk.BOTH,expand=True)
        self.centerWindow()


    def printStr(self):
        while self.stdoutq.qsize() and self.exit==False:
            try:
                msg=self.stdoutq.get()
                self.text.update()
                self.text.insert(tk.END,'# '+msg)
                self.text.see(tk.END)
            except Queue.Empty:
                pass
        self.after(100,self.printStr)


    def checkReady(self):
        if self.isexport.get()==1 or self.ishighlight.get()==1\
                or self.isnote.get()==1:
            self.hasaction=True
        else:
            self.hasaction=False

        if self.hasdb and self.hasout and self.hasaction:
            self.start_button.configure(state=tk.NORMAL)
            print('Menotexport Ready.')
        else:
            self.start_button.configure(state=tk.DISABLED)


    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text='Mendeley Data file:',\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text='Open',command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        hint='''
Default location on Linux:
~/.local/share/data/Mendeley\ Ltd./Mendeley\ Desktop/[email protected]
Default location on Windows:
C:\Users\Your_name\AppData\Local\Mendeley Ltd\Mendeley Desktop\[email protected]'''

        hint_label=tk.Label(frame,text=hint,\
                justify=tk.LEFT,anchor=tk.NW)
        hint_label.grid(row=1,column=0,columnspan=3,\
                sticky=tk.W,padx=8)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text='Output folder:',\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text='Choose',command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
        


    def openDir(self):
        self.out_entry.delete(0,tk.END)
        dirname=askdirectory()
        self.out_entry.insert(tk.END,dirname)
        if len(dirname)>0:
            print('Output folder: %s' %dirname)
            self.hasout=True
            self.checkReady()


    def openFile(self):
        self.db_entry.delete(0,tk.END)
        ftypes=[('sqlite files','*.sqlite'),('ALl files','*')]
        filename=askopenfilename(filetypes=ftypes)
        self.db_entry.insert(tk.END,filename)
        if len(filename)>0:
            print('Database file: %s' %filename)
            self.probeFolders()


    def probeFolders(self):
        dbfile=self.db_entry.get()
        try:
            db=sqlite3.connect(dbfile)
            query=\
            '''SELECT Documents.title,
                      DocumentFolders.folderid,
                      Folders.name
               FROM Documents
               LEFT JOIN DocumentFolders
                   ON Documents.id=DocumentFolders.documentId
               LEFT JOIN Folders
                   ON Folders.id=DocumentFolders.folderid
            '''
            ret=db.execute(query)
            data=ret.fetchall()
            df=pd.DataFrame(data=data,columns=['title',\
                    'folerid','name'])
            fetchField=lambda x, f: x[f].unique().tolist()
            folders=fetchField(df,'name')
            folders.sort()
            folders.remove(None)

            self.menfolderlist=['All',]+folders
            self.foldersmenu['values']=tuple(self.menfolderlist)
            self.foldersmenu.current(0)
            db.close()

            self.hasdb=True
            self.checkReady()

        except Exception as e:
            print('Failed to recoganize the given database file.') 
            print(e)





    
    def addActionFrame(self):

        frame=Frame(self,relief=tk.RAISED,borderwidth=1)
        frame.pack(fill=tk.X,side=tk.TOP,\
                expand=0,padx=8,pady=5)

        label=tk.Label(frame,text='Actions:',bg='#bbb')
        label.grid(row=0,column=0,sticky=tk.W,padx=8)

        #---------------Action checkbuttons---------------
        self.isexport=tk.IntVar()
        self.ishighlight=tk.IntVar()
        self.isnote=tk.IntVar()
        self.isseparate=tk.IntVar()

        self.check_export=tk.Checkbutton(frame,text='Export PDFs',\
                variable=self.isexport,command=self.doExport)

        self.check_highlight=tk.Checkbutton(frame,\
                text='Extract highlights',\
                variable=self.ishighlight,command=self.doHighlight)

        self.check_note=tk.Checkbutton(frame,\
                text='Extract notes',\
                variable=self.isnote,command=self.doNote)

        self.check_separate=tk.Checkbutton(frame,\
                text='Save separately',\
                variable=self.isseparate,command=self.doSeparate,\
                state=tk.DISABLED)

        frame.columnconfigure(0,weight=1)

        self.check_export.grid(row=0,column=1,padx=8,sticky=tk.W)
        self.check_highlight.grid(row=0,column=2,padx=8,sticky=tk.W)
        self.check_note.grid(row=0,column=3,padx=8,sticky=tk.W)
        self.check_separate.grid(row=0,column=4,padx=8,sticky=tk.W)

        #---------------------2nd row---------------------
        subframe=Frame(frame)
        subframe.grid(row=1,column=0,columnspan=5,sticky=tk.W+tk.E,\
                pady=5)

        #-------------------Folder options-------------------
        folderlabel=tk.Label(subframe,text='Mendeley folder:',\
                bg='#bbb')
        folderlabel.pack(side=tk.LEFT, padx=8)

        self.menfolder=tk.StringVar()
        self.menfolderlist=['All',]
        self.foldersmenu=Combobox(subframe,textvariable=\
                self.menfolder,values=self.menfolderlist,state='readonly')
        self.foldersmenu.current(0)
        self.foldersmenu.bind('<<ComboboxSelected>>',self.setfolder)
        self.foldersmenu.pack(side=tk.LEFT,padx=8)

        
        #-------------------Quit button-------------------
        quit_button=tk.Button(subframe,text='Quit',\
                command=self.quit)
        quit_button.pack(side=tk.RIGHT,padx=8)

        #-------------------Stop button-------------------
        '''
        self.stop_button=tk.Button(subframe,text='Stop',\
                command=self.stop)
        self.stop_button.pack(side=tk.RIGHT,padx=8)
        '''
                
        #-------------------Start button-------------------
        self.start_button=tk.Button(subframe,text='Start',\
                command=self.start,state=tk.DISABLED)
        self.start_button.pack(side=tk.RIGHT,pady=8)

        #-------------------Help button-------------------

        self.help_button=tk.Button(subframe,text='Help',\
                command=self.showHelp)
        self.help_button.pack(side=tk.RIGHT,padx=8)



    def setfolder(self,x):
        self.foldersmenu.selection_clear()
        self.menfolder=self.foldersmenu.get()
        self.foldersmenu.set(self.menfolder)
        if self.menfolder=='All':
            print('Work on all folders.')
        else:
            print('Select Mendeley folder: '+str(self.menfolder))



    def doExport(self):
        if self.isexport.get()==1:
            print('Export annotated PDFs.')
        else:
            print('Dont export annotated PDFs.')

        self.checkReady()



    def doHighlight(self):
        if self.ishighlight.get()==1:
            print('Extract highlighted texts.')
            self.check_separate.configure(state=tk.NORMAL)
        else:
            print('Dont extract highlighted texts.')
            if self.isnote.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
        self.checkReady()

    def doNote(self):
        if self.isnote.get()==1:
            print('Extract notes.')
            self.check_separate.configure(state=tk.NORMAL)
        else:
            print('Dont extract notes.')
            self.check_separate.state=tk.DISABLED
            if self.ishighlight.get()==0:
                self.check_separate.configure(state=tk.DISABLED)
        self.checkReady()


    def doSeparate(self):
        if self.isseparate.get()==1:
            print('Save annotations separately.')
        else:
            print('Save all annotations to single file.')



    def showHelp(self):
        helpstr='''
Menotexport v1.0\n\n
- Export PDFs: Bulk export PDFs with annotations to <output folder>.\n
- Extract highlights: Extract highlighted texts and output to a txt file in <output folder>.\n
- Extract highlights: Extract notes and output to a txt file in <output folder>.\n
- Save separately: If on, save each PDF's annotations to a separate txt.\n
- See README.md for more info.\n
'''

        tkMessageBox.showinfo(title='Help', message=helpstr)
        print(self.menfolder.get())




    def start(self):
        dbfile=self.db_entry.get()
        outdir=self.out_entry.get()
        action=[]
        if self.isexport.get()==1:
            action.append('e')
        if self.ishighlight.get()==1:
            action.append('m')
        if self.isnote.get()==1:
            action.append('n')
        if self.isseparate.get()==1:
            separate=True
        else:
            separate=False
            
        if 'e' in action or 'm' in action or 'n' in action:
            self.db_button.configure(state=tk.DISABLED)
            self.out_button.configure(state=tk.DISABLED)
            self.start_button.configure(state=tk.DISABLED)
            self.help_button.configure(state=tk.DISABLED)
            self.foldersmenu.configure(state=tk.DISABLED)
            self.check_export.configure(state=tk.DISABLED)
            self.check_highlight.configure(state=tk.DISABLED)
            self.check_note.configure(state=tk.DISABLED)
            self.check_separate.configure(state=tk.DISABLED)
	    self.messagelabel.configure(text='Message (working...)')

            folder=None if self.menfolder=='All' else [self.menfolder,]

            args=[dbfile,outdir,action,folder,True,True,separate,True]

            self.workthread=WorkThread('work',False,self.stateq)
            self.workthread.deamon=True

            self.workthread.args=args
            self.workthread.start()
            self.reset()
            '''
            self.workproc.apply_async(menotexport.main,args,\
                    callback=self.reset)
            self.workproc.join()
            '''



    def reset(self):
        while self.stateq.qsize() and self.exit==False:
            try:
                msg=self.stateq.get()
                if msg=='done':
                    self.db_button.configure(state=tk.NORMAL)
                    self.out_button.configure(state=tk.NORMAL)
                    self.start_button.configure(state=tk.NORMAL)
                    self.help_button.configure(state=tk.NORMAL)
                    self.foldersmenu.configure(state='readonly')
                    self.check_export.configure(state=tk.NORMAL)
                    self.check_highlight.configure(state=tk.NORMAL)
                    self.check_note.configure(state=tk.NORMAL)
                    self.check_separate.configure(state=tk.NORMAL)
                    self.messagelabel.configure(text='Message')
                    return
            except Queue.Empty:
                pass
        self.after(100,self.reset)


    
    def stop(self):
        #self.workthread.stop()
        pass
        

    def addMessageFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.BOTH,side=tk.TOP,\
                expand=1,padx=8,pady=5)

        self.messagelabel=tk.Label(frame,text='Message',bg='#bbb')
        self.messagelabel.pack(side=tk.TOP,fill=tk.X)

        self.text=tk.Text(frame)
        self.text.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.text.height=10

        scrollbar=tk.Scrollbar(self.text)
        scrollbar.pack(side=tk.RIGHT,fill=tk.Y)

        self.text.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text.yview)
Beispiel #33
0
 def __init__(self, parent, controller):
                 Frame.__init__(self, parent)
                 
                 #VARIABLES GLOBALES
                 global cod, cc, inquilino, codinm, inmueble, nit, owner, rel, vlrenta, duracion 
                 global contratos, tcontrato, incremento, gfacturaIni, facturaSgte, fecha, hoy 
                 global notas, anexos, destinacion, servicios, conexos, tercero, nombret, fecha
                 global aplicado, cc_aplicado, n_aplicado, inm_aplicado, novedad, n_nombre, n_valor
                 global h, busqueda, clean, update, add
                 
                 #INSTANCIEAS DE LOS WIDGETS
                 global e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, Cbx1, chkb1, chkb2, lb, cedulaE, notas
                 
                 fecha = datetime.date.today()
                 hoy = "%s" %fecha #ESTE NUESTRA LA FECHA EN FORMATO AÑO-MES-DIA (YYYY/MM/DD)
                 #hoy = time.strftime("%d/%m/%y") #ESTO PARA VER FORMATO FECHA EN DIA/MES/AÑO
                 #hoy = time.strftime("%y/%m/%d")
                 h = hoy
                 
                 #VARIABLES
                 lupa = PhotoImage(file='img/lupa.png')
                 schedule = PhotoImage(file='img/calendar.gif')
                 
                 cod = IntVar()
                 cc = StringVar()
                 inquilino = StringVar()
                 codinm = IntVar()
                 inmueble = StringVar()
                 nit = StringVar()
                 owner = StringVar()
                 rel = IntVar()
                 
                 vlrenta = DoubleVar()
                 duracion = IntVar()
                 contratos = ['Vivienda', 'Comercial', 'Mixta']
                 tcontrato = StringVar()
                 incremento = DoubleVar()
                 gfacturaIni = IntVar()
                 facturaSgte = IntVar()
                 fecha = StringVar()
                 
                 notas = StringVar()
                 anexos = StringVar()
                 destinacion = StringVar()
                 servicios = StringVar()
                 conexos = StringVar()
                 
                 tercero = StringVar()
                 nombret = StringVar()
                 
                 aplicado = IntVar()
                 cc_aplicado = StringVar()
                 n_aplicado = StringVar()
                 inm_aplicado = StringVar()
                 novedad = StringVar()
                 n_nombre = StringVar()
                 n_valor = DoubleVar()
                 
                 #BUSQUEDA = ["Nombre","CC/Nit"]
                 busqueda = StringVar()
                 busqueda.trace("w", lambda name, index, mode: buscar())
                 dato = StringVar()
                 
                 #WIDGETS
                 
                 #========================= HEADER ===========================
                 
                 self.header = Label(self, text="CONTRATOS", font="bold")
                 self.header.pack(pady=20, side=TOP)
                 
                 #========================== WRAPPER ==========================
                 
                 self.wrapper = Frame (self)
                 self.wrapper.pack(side=LEFT, fill=Y)
                 
                 #================ NOTEBOOK =============>
                 
                 self.nb = Notebook(self.wrapper)
                 
                 #-----------------------> TAB 1
                 
                 self.tab1 = Frame (self.nb)
                 
                 self.f0 = Frame(self.tab1)#-------------------------------------
                 self.f0.pack(pady=5,fill=X)
                 
                 l1 = Label(self.f0, text='Código:')
                 l1.pack(side=LEFT)
                 
                 e1 = Entry(self.f0, textvariable=cod, width=10)
                 e1.pack(side=LEFT)
                 
                 self.f1 = Frame(self.tab1)#-------------------------------------
                 self.f1.pack(pady=5,fill=X)
                 
                 l2 = Label(self.f1, text='Arrendatario:')
                 l2.pack(side=LEFT, fill=X)
                 
                 e2 = Entry(self.f1, textvariable=cc, width=15)
                 e2.pack(side=LEFT)
                 e2.bind('<Return>', buscarA)
                 
                 b1 = Button(self.f1, image=lupa, command=topArrendatario)
                 b1.image = lupa
                 b1.pack(side=LEFT)
                 
                 e3 = Entry(self.f1, textvariable=inquilino, state=DISABLED)
                 e3.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f2 = Frame(self.tab1)
                 self.f2.pack(pady=5,fill=X)#------------------------------------
                 
                 l3 = Label(self.f2, text='Inmueble:')
                 l3.pack(side=LEFT)
                 
                 e4 = Entry(self.f2, textvariable=codinm, width=10)
                 e4.pack(side=LEFT)
                 e4.bind('<Return>', buscarR)
                 
                 b2 = Button(self.f2, image=lupa, command=topRelacion)
                 b2.pack(side=LEFT)
                 
                 e5 = Entry(self.f2, textvariable=inmueble, state=DISABLED)
                 e5.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f3 = Frame(self.tab1)
                 self.f3.pack(pady=5,fill=X)#------------------------------------
                 
                 l4 = Label(self.f3, text='Propietario:')
                 l4.pack(side=LEFT)
                 
                 e6 = Entry(self.f3, width=15, textvariable=nit, state=DISABLED)
                 e6.pack(side=LEFT)
                 e7 = Entry(self.f3, width=5, textvariable=owner, state=DISABLED)
                 e7.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f4 = Frame(self.tab1)
                 self.f4.pack(pady=5,fill=X)#------------------------------------
                 
                 self.arriendo = Label(self.f4, text='Arriendo $:')
                 self.arriendo.pack(side=LEFT)
                 e8 = Entry(self.f4, textvariable=vlrenta, state=DISABLED, width=20)
                 e8.pack(side=LEFT)
                 
                 self.duracion = Label(self.f4, text='Duración Contrato:')
                 self.duracion.pack(side=LEFT)
                 e9 = Entry(self.f4, textvariable=duracion, width=5)
                 e9.pack(side=LEFT)
                 
                 self.meses = Label(self.f4, text='Meses')
                 self.meses.pack(side=LEFT)
                 
                 self.f5 = Frame(self.tab1)
                 self.f5.pack(pady=5,fill=X)#------------------------------------
                 
                 self.tcontrato = Label(self.f5, text='Tipo Contrato:')
                 self.tcontrato.pack(side=LEFT)
                 
                 Cbx1 = Combobox(self.f5, textvariable=tcontrato, values=contratos, width=10)
                 Cbx1.set('')
                 Cbx1.pack(side=LEFT)
                 
                 self.incremento = Label(self.f5, text='Incremento:')
                 self.incremento.pack(side=LEFT)
                 e10 = Entry(self.f5, textvariable=incremento, width=5)
                 e10.pack(side=LEFT)
                 
                 chkb1 = Checkbutton(self.f5, text="General factura\n inicial", variable=gfacturaIni)
                 chkb1.pack(side=LEFT)
                 chkb2 = Checkbutton(self.f5, text="Facturar príodo\n siguiente", variable=facturaSgte)
                 chkb2.pack(side=LEFT)
                 
                 self.f6 = Frame(self.tab1)
                 self.f6.pack(pady=5,fill=X)#------------------------------------
                 
                 btime = Button(self.f6, image=schedule, command=calendario)
                 btime.image = schedule
                 btime.pack(side=RIGHT)
                 
                 etime = Entry(self.f6, textvariable=fecha, width=10)
                 fecha.set(hoy)
                 etime.pack(side=RIGHT)
                 
                 #ltime = Label(self.f6, text=hoy, font="bold", foreground='red')
                 #ltime.pack(side=RIGHT)
                 
                 self.fi = Label(self.f6, text='Fecha Inicio: ')
                 self.fi.pack(side=RIGHT)
                 
                 self.tab1.pack()
                 
                 #-----------------------> TAB 2
                 
                 self.tab2 = Frame (self.nb)
                 self.tab2.pack()
                 
                 self.f7 = Frame(self.tab2)#-------------------------------------
                 self.f7.pack(fill=X, pady=10)
                 
                 notas = Text(self.f7, height=5)
                 notas.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f8 = Frame(self.tab2)
                 self.f8.pack(pady=5,fill=X)#-------------------------------------------
                 
                 self.destino = Label(self.f8, text='Destinación:')
                 self.destino.pack(side=LEFT)
                 self.destinoE = Entry(self.f8, textvariable=destinacion, width=5)
                 self.destinoE.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f9 = Frame(self.tab2)
                 self.f9.pack(pady=5,fill=X)#-------------------------------------------
                 
                 self.servicios = Label(self.f9, text='Servicios adicionales:')
                 self.servicios.pack(side=LEFT)
                 self.serviciosE = Entry(self.f9, textvariable=servicios, width=5)
                 self.serviciosE.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f10 = Frame(self.tab2)
                 self.f10.pack(pady=5,fill=X)#-------------------------------------------
                 
                 self.conexos = Label(self.f10, text='Conexos:')
                 self.conexos.pack(side=LEFT)
                 self.conexosE = Entry(self.f10, textvariable=conexos, width=5)
                 self.conexosE.pack(side=LEFT, fill=X, expand=1)
                 
                 #-----------------------> TAB 3
                 
                 self.tab3 = Frame (self.nb)
                 self.tab3.pack()
                 
                 self.f11 = Frame(self.tab3)#-------------------------------------
                 self.f11.pack(fill=X, pady=5)
                 
                 self.cedula = Label (self.f11, text='CC/Nit: ')
                 self.cedula.pack(side=LEFT)
                 
                 cedulaE = Entry(self.f11, textvariable=tercero, width=15)
                 cedulaE.pack(side=LEFT)
                 cedulaE.bind('<Return>', buscarT)
                 
                 b4 = Button(self.f11, image=lupa, command=topTercero)
                 b4.image = lupa
                 b4.pack(side=LEFT)
                 
                 self.f12 = Frame(self.tab3) #-------------------------------------
                 self.f12.pack(fill=X, pady=5)
                 
                 self.tercero = Label (self.f12, text='Nombre: ')
                 self.tercero.pack(side=LEFT)
                 
                 self.terceroE = Entry(self.f12, textvariable=nombret, width=5, state=DISABLED)
                 self.terceroE.pack(side=LEFT, fill=X, expand=1)
                 
                 #-----------------------> TAB 4
                 
                 self.tab4 = Frame (self.nb)
                 self.tab4.pack()
                 
                 self.f13 = Frame(self.tab4) #-------------------------------------
                 self.f13.pack(fill=X, pady=5)
                 
                 l = Label (self.f13, text='Aplicar a: ')
                 l.pack(side=LEFT)
                 
                 Ch = Checkbutton(self.f13, text="Propietario", variable=aplicado)
                 Ch.pack(side=LEFT)
                 
                 self.f14 = Frame(self.tab4) #-------------------------------------
                 self.f14.pack(fill=X, pady=5)
                 
                 l13 = Label (self.f14, text='CC/Nit: ')
                 l13.pack(side=LEFT)
                 
                 e13 = Entry(self.f14, textvariable=cc_aplicado, width=15)
                 e13.pack(side=LEFT)
                 
                 b13 = Button(self.f14, image=lupa, command=None)
                 b13.image = lupa
                 b13.pack(side=LEFT)
                 
                 e13 = Entry(self.f14, textvariable=n_aplicado, state=DISABLED)
                 e13.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f15 = Frame(self.tab4)
                 self.f15.pack(fill=X, pady=5)#------------------------------------
                 
                 l14 = Label(self.f15, text='Cod.Inmueble:')
                 l14.pack(side=LEFT)
                 
                 e14 = Entry(self.f15, textvariable=inm_aplicado, width=5, state=DISABLED)
                 e14.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f16 = Frame(self.tab4)
                 self.f16.pack(fill=X, pady=5)#------------------------------------
                 
                 l16 = Label(self.f16, text='Novedad:')
                 l16.pack(side=LEFT, fill=X)
                 
                 e16 = Entry(self.f16, textvariable=novedad, width=15)
                 e16.pack(side=LEFT)
                 
                 b16 = Button(self.f16, image=lupa, command=None)
                 b16.image = lupa
                 b16.pack(side=LEFT)
                 
                 e16 = Entry(self.f16, textvariable=n_nombre, state=DISABLED)
                 e16.pack(side=LEFT, fill=X, expand=1)
                 
                 self.f17 = Frame(self.tab4)
                 self.f17.pack(fill=X, pady=5)#------------------------------------
                 
                 l17 = Label(self.f17, text='Vlr Novedad:')
                 l17.pack(side=LEFT, fill=X)
                 
                 e17 = Entry(self.f17, textvariable=n_valor, width=15)
                 e17.pack(side=LEFT)
                 
                 #---------------------------------------------------------------
                 
                 self.nb.add (self.tab1, text="General")
                 self.nb.add(self.tab2, text="Anexos")
                 self.nb.add(self.tab3, text="Tercero")
                 self.nb.add(self.tab4, text="Gasto fijo")
                 
                 self.nb.pack()
                 
                 self.fBtn = Frame(self.wrapper)
                 self.fBtn.pack()#-------------------------------
                 
                 clean = Button(self.fBtn, text='Limpiar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
                 clean.pack(side=RIGHT)
                 
                 update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=actualizar, state=DISABLED)
                 update.pack(side=RIGHT)
                 
                 add = Button(self.fBtn, text='Agregar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar)
                 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 CONTRATOS")
                 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)
                 lb.bind("<Double-Button-1>", callback)
                 
                 self.wrap2 = Frame(self.aside)
                 self.wrap2.pack()
                 
                 show = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar)
                 show.pack(fill=X)
                 
                 delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
                 delete.pack(fill=X)
                 
                 edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar)
                 edit.pack(fill=X)
                 
                 buscador = Label(self.wrap2, text="Buscar por CC:")
                 buscador.pack()
                 E = Entry(self.wrap2, textvariable=busqueda, width=24)
                 E.pack()
Beispiel #34
0
class App:
    """Main class for the gui layer."""

    def __init__(self, master):
        self.master = master
        self.master.title("Gaussian Elimination / Jacobi Method")
        self.create_widgets(master)
        # options for opening or saving a file
        self.file_opt = options = {}
        options['filetypes'] = [('all files', '*'), ('text files', '.txt'),
                                ('csv files', '.csv')]

    def create_widgets(self, master):
        """Populate the main window with gui components."""
        # buttons, slider, combobox etc.
        frame0 = Frame(master)
        frame0.grid(row=1, column=0, sticky=N)
        self.scale = Scale(frame0, from_=2, to=2000, orient=HORIZONTAL,
                           label='Matrix / vector size (n):')
        self.scale.pack(fill="x")
        btn_gen_mtx = Button(frame0, text="Generate matrix A (n x n)",
                             command=self.gen_mtx)
        btn_gen_mtx.pack(fill="x")
        btn_gen_vec = Button(frame0, text="Generate vector B (n)",
                             command=self.gen_vec)
        btn_gen_vec.pack(fill="x")
        btn_load_mtx = Button(frame0, text="Load matrix A",
                              command=self.load_mtx)
        btn_load_mtx.pack(fill="x")
        btn_load_vec = Button(frame0, text="Load vector B",
                              command=self.load_vec)
        btn_load_vec.pack(fill="x")
        btn_solve = Button(frame0, text="SOLVE",
                           command=self.solve)
        btn_solve.pack(fill="x")
        self.combobox = Combobox(frame0, state="readonly",
                                 values=("Gauss Method", "Jacobi Method",
                                         "numpy.linalg.solve()"))
        self.combobox.pack(fill="x")
        self.combobox.set("Gauss Method")  # default choice
        btn_quit = Button(frame0, text="Quit", command=self.quit)
        btn_quit.pack(fill='x', pady=28)

        # scrollbar text widget (matrix a)
        self.frame1 = Frame(master)
        xscrollbar1 = Scrollbar(self.frame1, orient=HORIZONTAL)
        xscrollbar1.grid(row=1, column=0, sticky=E+W)
        yscrollbar1 = Scrollbar(self.frame1)
        yscrollbar1.grid(row=0, column=1, sticky=N+S)
        self.text1 = Text(self.frame1, wrap=NONE, bd=0, state=DISABLED,
                          xscrollcommand=xscrollbar1.set,
                          yscrollcommand=yscrollbar1.set)
        self.text1.grid(row=0, column=0, sticky=N+S+W+E)
        xscrollbar1.config(command=self.text1.xview)
        yscrollbar1.config(command=self.text1.yview)
        self.frame1.grid_rowconfigure(0, weight=1)
        self.frame1.grid_columnconfigure(0, weight=1)
        self.frame1.grid(row=1, column=1, sticky=N+S+W+E)

        # scrollbar text widget (vector b)
        self.frame2 = Frame(master)
        xscrollbar2 = Scrollbar(self.frame2, orient=HORIZONTAL)
        xscrollbar2.grid(row=1, column=0, sticky=E+W)
        yscrollbar2 = Scrollbar(self.frame2)
        yscrollbar2.grid(row=0, column=1, sticky=N+S)
        self.text2 = Text(self.frame2, width=30, wrap=NONE, bd=0,
                          state=DISABLED, xscrollcommand=xscrollbar2.set,
                          yscrollcommand=yscrollbar2.set)
        self.text2.grid(row=0, column=0, sticky=N+S+E+W)
        xscrollbar2.config(command=self.text2.xview)
        yscrollbar2.config(command=self.text2.yview)
        self.frame2.grid_rowconfigure(0, weight=1)
        self.frame2.grid_columnconfigure(0, weight=1)
        self.frame2.grid(row=1, column=2, sticky=N+S)

        # scrollbar text widget (vector x)
        self.frame3 = Frame(master)
        xscrollbar3 = Scrollbar(self.frame3, orient=HORIZONTAL)
        xscrollbar3.grid(row=1, column=0, sticky=E+W)
        yscrollbar3 = Scrollbar(self.frame3)
        yscrollbar3.grid(row=0, column=1, sticky=N+S)
        self.text3 = Text(self.frame3, width=30, wrap=NONE, bd=0,
                          state=DISABLED, xscrollcommand=xscrollbar3.set,
                          yscrollcommand=yscrollbar3.set)
        self.text3.grid(row=0, column=0, sticky=N+S+E+W)
        xscrollbar3.config(command=self.text3.xview)
        yscrollbar3.config(command=self.text3.yview)
        self.frame3.grid_rowconfigure(0, weight=1)
        self.frame3.grid_columnconfigure(0, weight=1)
        self.frame3.grid(row=1, column=3, sticky=N+S)

        # labels
        label1 = Label(master, text="Matrix A")
        label1.grid(row=0, column=1)
        label2 = Label(master, text="Vector B")
        label2.grid(row=0, column=2)
        label3 = Label(master, text="Vector X")
        label3.grid(row=0, column=3)
        self.bottom_label = Label(master)
        self.bottom_label.grid(row=2, column=0, columnspan=4, sticky=W+E)

        # which row/column should grow/shrink when resizing the main window
        self.master.grid_rowconfigure(1, weight=1)
        self.master.grid_columnconfigure(1, weight=1)

    def quit(self):
        """A callback method for quitting the app."""
        self.master.destroy()

    def gen_mtx(self):
        """A callback method for generating matrix A."""
        self.bottom_label.config(text='')
        self.subp_launcher(ngm.posdef_diag_dom, self.scale.get())
        self.cw = CancelWindow(self.master, self.subp)

    def gen_vec(self):
        """A callback method for generating vector B."""
        self.bottom_label.config(text='')
        self.subp_launcher(ngm.gen_rnd_vec, self.scale.get())
        self.cw = CancelWindow(self.master, self.subp)

    def load_mtx(self):
        """A callback method for loading matrix A."""
        # TODO: add a handler for exceptions raised by nmgj.check_input_data()
        self.bottom_label.config(text='')
        filename = tkFileDialog.askopenfilename(**self.file_opt)
        if filename:
            self.a = nmgj.load_mtx(filename)
            self.display_text(self.text1, self.a)

    def load_vec(self):
        """A callback method for loading vector B."""
        self.bottom_label.config(text='')
        filename = tkFileDialog.askopenfilename(**self.file_opt)
        if filename:
            self.b = nmgj.load_vec(filename)
            self.display_text(self.text2, self.b)

    def delete_text(self, text_wgt):
        """A helper function for text widget refreshing."""
        text_wgt.config(state=NORMAL)
        text_wgt.delete(1.0, END)
        text_wgt.config(state=DISABLED)

    def display_text(self, text_wgt, text):
        """A helper function for text widget refreshing."""
        text_wgt.config(state=NORMAL)
        text_wgt.delete(1.0, END)
        if text is not None:
            text_wgt.insert(END, text)
        text_wgt.config(state=DISABLED)

    def solve(self):
        """A callback method for solving a given set of equations."""
        self.x = None
        self.delete_text(self.text3)
        if (self.a is None or self.b is None) or (len(self.a) != len(self.b)):
            # TODO: consider different error message for the 'None' case
            tkMessageBox.showerror("Error", "Dimensions mismatch.")
            return
        choice = self.combobox.get()
        f = {
            "Gauss Method": nmgj.gauss,
            "Jacobi Method": nmgj.jacobi,
            "numpy.linalg.solve()": nmgj.la.solve,
        }.get(choice)
        self.subp_launcher(f, self.a, self.b)
        self.cw = CancelWindow(self.master, self.subp)

    def calc_residual(self, a, x, b):
        """Handles calculation of residual & dislpaying the results."""
        self.res_min, self.res_avg, self.res_max = nmgj.calc_residual(a, x, b)
        self.display_text(self.text3, self.x)
        self.bottom_label.config(text='Residual:    min ' + str(self.res_min) +
                                      '    avg ' + str(self.res_avg) +
                                      '    max ' + str(self.res_max))

    def subp_launcher(self, f, *args):
        """Creates a queue for communication, spawns the subprocess and
        schedules checking if it's still active.
        """
        # note: there will be no more than one subprocess at any given time
        self.q = mp.Queue()
        self.subp = mp.Process(target=self.subp_wrapper, args=(f, args))
        self.subp.start()
        #print "subprocess started - pid:", self.subp.pid  # for diagnostics
        self.check_subp(f)

    def subp_wrapper(self, f, args):
        """Wraps the subprocess f, creates the temp file for data passing and
        puts its name on the queue.
        """
        results = f(*args)
        # Generally, out-of-band signalling is better than in-band signalling -
        # hence temporary file for data, and queue for communication *only*.
        # And also, although you can safely put objects up to 32 MB through
        # the queue, there's a 'hidden' pipe mechanism involved here (with its
        # own limits), so the order in which you use join() and get() methods
        # may be sigificant (see: http://bugs.python.org/issue8426).
        with NamedTemporaryFile(delete=False) as temp:
            np.savez(temp, results)
            temp.flush()
            self.q.put(temp.name)

    def check_subp(self, f):
        """Checks if the subprocess is still alive, otherwise does the cleanup."""
        if self.subp.is_alive() is False:
            if self.subp.exitcode > 0:
                self.subp.terminate()
            self.subp.join()
            #print 'subprocess finished'  # for diagnostics
            self.subp_cleanup(f)
            return
        self.master.after(100, self.check_subp, f)  # every 100 ms

    def subp_cleanup(self, f):
        """Cleans up after the calculations, displays the solution."""
        if self.q.empty() is not True:
            temp = self.q.get()
            results = np.load(temp).items()[0][1]
            os.remove(temp)
        else:
            results = None
        if f == ngm.posdef_diag_dom:
            self.a = results
            self.display_text(self.text1, self.a)
        elif f == ngm.gen_rnd_vec:
            self.b = results
            self.display_text(self.text2, self.b)
        elif f in (nmgj.gauss, nmgj.jacobi, nmgj.la.solve):
            self.x = results
            self.display_text(self.text3, results)
            if self.x is not None:
                self.calc_residual(self.a, self.x, self.b)
Beispiel #35
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)
Beispiel #36
0
class UIBidding(Notify):


    class CoincheException(Exception):
        def __init__(self, pid):
            self.pid = pid


    def __init__(self, root, x, y, size_x, size_y):
        Notify.__init__(self)

        # Memorise the frame
        self._root = root 

        self._frame = Frame(width = size_x, height = size_y) 
        # No resize
        self._frame.pack_propagate(0)
        # Style
        self._frame.config(borderwidth = 5)

        self._x = x
        self._y = y

        # Init the buttons
        self._init_buttons()

        # Will be used to notify the main thread when waiting for a call 
        self.need_bid_event = Event() 
        # Will be used to notify the main thread when waiting for a coinche 
        self.coinche_event = Event() 

        self.pid = 0
        self._last_bid = None 
        
        self.enable()
     
    def display(self): 
        """
            Display the widget on the table

        """
        self._frame.place(in_ = self._root, x = self._x, y = self._y)


    def hide(self):
        """
            Hide the pannel when the biddings are closed for example

        """
        self._frame.place_forget()


    def _init_color_buttons(self):
        """
            Init the buttons to select the color

        """
        # Dedicated frame for buttons
        self._buttons_frame = Frame()
        # This dictionnary will contains all the color buttons
        self._buttons = dict()
        # Several colors are available
        colors = list(Bidding.colors)
        colors.pop()
        # The buttons need to have a fixed size
        h = 2
        w = 2

        for c in colors:
            self._buttons[c] = Button(self._buttons_frame, text=c, \
                                      height=h, width=w, \
                                      command=lambda c=c: self._click_color(c))
            self._buttons[c].pack(side = LEFT)

        # Pack the dedicated frame into the main frame
        self._buttons_frame.pack(in_ = self._frame)

        self._selected_color = None 


    def _init_value_box(self):
        """
            Init the list box which select the value of the bid

        """
        availableValue = Bidding.values 
        # TODO: display "pass" instead of "0"
        #availableValue[0] = "pass"
        self._value_box = Combobox(self._frame, \
                                   values = availableValue, \
                                   # TODO
                                   # Only justify the selected value
                                   #justify = RIGHT, \
                                   state = 'readonly')
        self._value_box.bind("<<ComboboxSelected>>", lambda x: self._update_bid_button())
        self._value_box.set(availableValue[0])
        self._value_box.pack(fill = X)


    @staticmethod
    def raise_(e):
        raise e


    def _init_bid_button(self):
        # To bid
        self._bid_button = Button(self._frame, text = "Pass", \
                                  command = self._click_bidding)
        self._bid_button.pack(fill = X)
        # To coinche
        self._coinche_button = Button(self._frame, text = "Coinche", \
                command = lambda: self._event[EVT_UI_COINCHE]()) 
        self._coinche_button.pack(fill = X)


    def _init_buttons(self):
        """
            Init the buttons 

        """
        # Put the value box on top of the buttons
        self._init_value_box()
        self._init_color_buttons()
        self._init_bid_button() 


    def _click_color(self, color):
        self._selected_color = color 
        self._update_bid_button()


    def _click_bidding(self):
        """
            Callback function on bidding click  

        """
        if self._bid_button.config('text')[-1] == "Pass":
            self._last_bid = Bidding(self.pid)
        else:
            if self._selected_color is None:
                self._event[CONSOLE_RED]("Choose a color!")
                return
            c = self._selected_color
            v = int(self._value_box.get())
            self._last_bid = Bidding(self.pid, v, c) 
        # Notify the consumer (main thread)
        self.need_bid_event.set()
        # Reset the event
        self.need_bid_event.clear()


    def _click_coinche(self):
        # Notify the consumer
        self.coinche_event.set()
        # Reset the event
        self.coinche_event.clear()


    def _update_bid_button(self):
        value = self._value_box.get()
        color = self._selected_color
        if value == "0" and color is None:
            self._bid_button.config(text = "Pass")
        elif value == "0":
            self._bid_button.config(text = "Bid " + color)
        elif color is None: 
            self._bid_button.config(text = "Bid " + value)
        else:
            self._bid_button.config(text = "Bid " + value + " " + color)


    @property
    def last_bid(self):
        return self._last_bid


    @last_bid.setter
    def last_bid(self, value):
        if value is None:
            self._bid_button.config(text = "Pass")
            self._last_bid = None 
        else:
            raise Exception("Should not be called")


    def disable(self):
        """
            Disable the bid button

        """
        self._bid_button.config(state = DISABLED)


    def enable(self):
        """
            Enable the bid button

        """
        self._bid_button.config(state = NORMAL)
Beispiel #37
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        #VARIABLES GLOBALES
        global cedula, titulo, ingreso, rsocial, residencia, nombres, apellidos, direccion, telefono, oficina, tel, telfax, correo, cumpleanos, dia, mes, envio, celular, tipopersona, comision, retefuente, reteiva, gcontribuyente, gfactura, gcheque, reprecc, reprenombres, repredireccion, repretelefono, repreoficina, repretel, reprebanco, repretcuenta, reprenumcuenta, tit1cc, tit1nombres, tit1banco, tit1tcuenta, tit1numcuenta, tit2cc, tit2nombres, tit2banco, tit2tcuenta, tit2numcuenta, lb, note, popmenu, busqueda, dato, E
        #INSTANCIEAS DE LOS WIDGETS
        global ccE, refE, dateinE, socialE, cityE, nameE, lnameE, adressE, phoneE, officeE, officetelE, telfaxE, emailE, birthdayE, birthdayCbx, mailE, mobileE, personR1, personR2, comisionE, Ch1, Ch2, Ch3, Ch4, Ch5, note, cc0E, name0E, adress0E, phone0E, office0E, officetel0E, bank0Cbx, tbank0Cbx, tcuenta0E, cc1E, name1E, bank1Cbx, tbank1Cbx, tcuenta1E, cc2E, name2E, bank2Cbx, tbank2Cbx, tcuenta2E, add, update, delete, clean
        global info, lists, _propietarios

        _propietarios = dict()
        lists = []

        #Variables
        cedula = StringVar()
        titulo = StringVar()
        ingreso = StringVar()
        rsocial = StringVar()
        residencia = StringVar()
        nombres = StringVar()
        apellidos = StringVar()
        direccion = StringVar()
        telefono = StringVar()
        oficina = StringVar()
        tel = StringVar()
        telfax = StringVar()
        correo = StringVar()
        dia = IntVar()
        mes = StringVar()
        envio = StringVar()
        celular = StringVar()
        tipopersona = IntVar()
        comision = DoubleVar()
        retefuente = IntVar()
        reteiva = IntVar()
        gcontribuyente = IntVar()
        gfactura = IntVar()
        gcheque = IntVar()
        notas = StringVar()

        #----------------------------

        reprecc = StringVar()
        reprenombres = StringVar()
        repredireccion = StringVar()
        repretelefono = StringVar()
        repreoficina = StringVar()
        repretel = StringVar()
        reprebanco = StringVar()
        repretcuenta = StringVar()
        reprenumcuenta = StringVar()

        tit1cc = StringVar()
        tit1nombres = StringVar()
        tit1banco = StringVar()
        tit1tcuenta = StringVar()
        tit1numcuenta = StringVar()

        tit2cc = StringVar()
        tit2nombres = StringVar()
        tit2banco = StringVar()
        tit2tcuenta = StringVar()
        tit2numcuenta = StringVar()

        meses = [
            "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
            "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
        ]
        tbancos = [
            'Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"
        ]

        tbanktype = ['Corriente', 'Ahorro']

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

        # MENU DEL MOUSE

        popmenu = Menu(self, tearoff=0)
        popmenu.add_command(label="Imprimir", command=hello)
        popmenu.add_command(label="Cargar", command=modificar)
        popmenu.add_command(label="Eliminar", command=borrar)
        #popmenu.add_separator()
        popmenu.bind('<Escape>', release)

        #WIDGETS

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

        self.header = Label(self, text="GESTIÓN DE PROPIETARIOS", font="bold")
        self.header.pack(pady=20, side=TOP)

        #========================== WRAPPER ============================
        #Contiene los Notebooks con los campos formulario

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

        #================ NOTEBOOK =============>

        self.nb = Notebook(self.wrapper)

        #-----------------------> TAB 1

        self.tab1 = Frame(self.nb)

        self.f0 = Frame(self.tab1)  #Para dejar espacio entre Tab y Label
        self.f0.pack(fill=X, pady=10)  #-------------------------------

        #========================= PERSONALES ==========================

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

        self.ccL = Label(self.f1, text='CC/Nit:')
        self.ccL.pack(side=LEFT)
        ccE = Entry(self.f1, textvariable=cedula)
        ccE.pack(side=LEFT, fill=X, expand=1)
        ccE.focus_set()

        self.refL = Label(self.f1, text='Título:')
        self.refL.pack(side=LEFT)
        refE = Entry(self.f1, textvariable=titulo, width=10)
        refE.pack(side=LEFT)
        #refE.bind("<KeyRelease>", caps)

        self.dateinL = Label(self.f1, text='Fecha Ingreso:')
        self.dateinL.pack(side=LEFT)
        dateinE = Entry(self.f1,
                        textvariable=ingreso,
                        width=10,
                        state=DISABLED)
        ingreso.set("0000-00-00")
        dateinE.pack(side=LEFT)

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

        self.socialL = Label(self.f2, text='Razón Social:')
        self.socialL.pack(side=LEFT)
        socialE = Entry(self.f2, textvariable=rsocial)
        socialE.pack(side=LEFT, fill=X, expand=1)
        socialE.bind("<KeyRelease>", caps)

        self.cityL = Label(self.f2, text='Ciudad de residencia:')
        self.cityL.pack(side=LEFT)
        cityE = Entry(self.f2, textvariable=residencia, width=15)
        cityE.pack(side=LEFT)
        cityE.bind("<KeyRelease>", caps)

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

        self.nameL = Label(self.f3, text='Nombres:')
        self.nameL.pack(side=LEFT)
        nameE = Entry(self.f3, textvariable=nombres)
        nameE.pack(side=LEFT, fill=X, expand=1)
        nameE.bind("<KeyRelease>", caps)

        self.lnameL = Label(self.f3, text='Apellidos:')
        self.lnameL.pack(side=LEFT)
        lnameE = Entry(self.f3, textvariable=apellidos)
        lnameE.pack(side=LEFT, fill=X, expand=1)
        lnameE.bind("<KeyRelease>", caps)

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

        self.adressL = Label(self.f4, text='Dir. Casa:')
        self.adressL.pack(side=LEFT)
        adressE = Entry(self.f4, textvariable=direccion)
        adressE.pack(side=LEFT, fill=X, expand=1)
        adressE.bind("<KeyRelease>", caps)

        self.phoneL = Label(self.f4, text='Tel:')
        self.phoneL.pack(side=LEFT)
        phoneE = Entry(self.f4, textvariable=telefono, width=20)
        phoneE.pack(side=LEFT)

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

        self.officeL = Label(self.f5, text='Dir. Oficina:')
        self.officeL.pack(side=LEFT)
        officeE = Entry(self.f5, textvariable=oficina, width=20)
        officeE.pack(side=LEFT, fill=X, expand=1)
        officeE.bind("<KeyRelease>", caps)

        self.officetelL = Label(self.f5, text='Tel:')
        self.officetelL.pack(side=LEFT)
        officetelE = Entry(self.f5, textvariable=tel, width=15)
        officetelE.pack(fill=X, side=LEFT)

        self.telfaxL = Label(self.f5, text='Tel. Fax:')
        self.telfaxL.pack(side=LEFT)
        telfaxE = Entry(self.f5, textvariable=telfax, width=10)
        telfaxE.pack(side=LEFT)

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

        self.emailL = Label(self.f6, text='Email:')
        self.emailL.pack(side=LEFT)
        emailE = Entry(self.f6, textvariable=correo, width=30)
        emailE.pack(side=LEFT)

        self.birthdayL = Label(self.f6, text='Cumpleaños:')
        self.birthdayL.pack(side=LEFT)

        self.birthdayL2 = Label(self.f6, text='Día:')
        self.birthdayL2.pack(padx=5, side=LEFT)

        #s = Spinbox(self.f6, from_=1, to=31,textvariable=dia, width=3)
        #s.pack(side=LEFT)

        birthdayE = Entry(self.f6, textvariable=dia, width=3)
        birthdayE.pack(side=LEFT)

        self.birthdayL3 = Label(self.f6, text='Mes:')
        self.birthdayL3.pack(padx=5, side=LEFT)

        birthdayCbx = Combobox(self.f6,
                               textvariable=mes,
                               values=meses,
                               width=10)
        birthdayCbx.set('Enero')
        birthdayCbx.pack(side=LEFT)

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

        self.mailL = Label(self.f7, text='Dir. Correspondencia:')
        self.mailL.pack(side=LEFT)
        mailE = Entry(self.f7, textvariable=envio)
        mailE.pack(side=LEFT, fill=X, expand=1)
        mailE.bind("<KeyRelease>", caps)

        self.mobileL = Label(self.f7, text='Celular:')
        self.mobileL.pack(side=LEFT)
        mobileE = Entry(self.f7, textvariable=celular, width=10)
        mobileE.pack(side=LEFT, fill=X, expand=1)

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

        self.personL = Label(self.f8, text='Tipo Persona:')
        self.personL.pack(side=LEFT)

        personR1 = Radiobutton(self.f8,
                               text="Natural",
                               variable=tipopersona,
                               value=1)
        personR1.pack(padx=20, side=LEFT)

        personR2 = Radiobutton(self.f8,
                               text="Jurídica",
                               variable=tipopersona,
                               value=2)
        personR2.pack(padx=20, side=LEFT)

        self.comisionL = Label(self.f8, text='$ Comisión:')
        self.comisionL.pack(side=LEFT)

        comisionE = Entry(self.f8, textvariable=comision, width=5)
        comisionE.pack(side=LEFT)

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

        Ch1 = Checkbutton(self.f, text="Retefuente", variable=retefuente)
        Ch1.pack(side=LEFT)

        Ch2 = Checkbutton(self.f, text="Rete IVA", variable=reteiva)
        Ch2.pack(side=LEFT)

        Ch3 = Checkbutton(self.f,
                          text="Gran Contribuyente",
                          variable=gcontribuyente)
        Ch3.pack(side=LEFT)

        Ch4 = Checkbutton(self.f, text="Genera Factura", variable=gfactura)
        Ch4.pack(side=LEFT)

        Ch5 = Checkbutton(self.f, text="Genera Cheque", variable=gcheque)
        Ch5.pack(side=LEFT)

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

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

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

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

        self.tab1.pack()

        #-----------------------> TAB 2

        self.tab2 = Frame(self.nb)
        self.tab2.pack()

        self.f0 = Frame(self.tab2)  #Para dejar espacio entre Tab y Label
        self.f0.pack(fill=X, pady=10)  #----------------------------------

        #======================= COMPLEMENTARIOS =======================

        self.lf = LabelFrame(self.tab2, text="Datos Representante")

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

        self.ccRL = Label(self.f0, text='CC:')
        self.ccRL.pack(side=LEFT)
        cc0E = Entry(self.f0, textvariable=reprecc, width=10)
        cc0E.pack(side=LEFT, fill=X, expand=1)

        self.nameL = Label(self.f0, text='Nombres:')
        self.nameL.pack(side=LEFT)
        name0E = Entry(self.f0, textvariable=reprenombres)
        name0E.pack(side=LEFT, fill=X, expand=1)
        name0E.bind("<KeyRelease>", caps)

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

        self.adressL = Label(self.f1, text='Dir. Casa:')
        self.adressL.pack(side=LEFT)
        adress0E = Entry(self.f1, textvariable=repredireccion)
        adress0E.pack(side=LEFT, fill=X, expand=1)
        adress0E.bind("<KeyRelease>", caps)

        self.phoneL = Label(self.f1, text='Tel:')
        self.phoneL.pack(side=LEFT)
        phone0E = Entry(self.f1, textvariable=repretelefono, width=20)
        phone0E.pack(side=LEFT)

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

        self.officeL = Label(self.f2, text='Dir. Oficina:')
        self.officeL.pack(side=LEFT)
        office0E = Entry(self.f2, textvariable=repreoficina)
        office0E.pack(side=LEFT, fill=X, expand=1)
        office0E.bind("<KeyRelease>", caps)

        self.officetelL = Label(self.f2, text='Tel:')
        self.officetelL.pack(side=LEFT)
        officetel0E = Entry(self.f2, textvariable=repretel, width=20)
        officetel0E.pack(fill=X, side=LEFT)

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

        self.tbancpL = Label(self.f3, text='Banco:')
        self.tbancpL.pack(side=LEFT)
        bank0Cbx = Combobox(self.f3,
                            textvariable=reprebanco,
                            values=tbancos,
                            width=12)
        bank0Cbx.set('')
        bank0Cbx.pack(side=LEFT)

        self.tbancpL = Label(self.f3, text='Tipo Cuenta:')
        self.tbancpL.pack(side=LEFT)
        tbank0Cbx = Combobox(self.f3,
                             textvariable=repretcuenta,
                             values=tbanktype,
                             width=8)
        tbank0Cbx.set('')
        tbank0Cbx.pack(side=LEFT)

        self.tcuentaL = Label(self.f3, text='# Cuenta:')
        self.tcuentaL.pack(side=LEFT)
        tcuenta0E = Entry(self.f3, textvariable=reprenumcuenta)
        tcuenta0E.pack(side=LEFT, fill=X, expand=1)

        self.lf.pack(fill=X, ipady=5)  #==================================

        self.f0 = Frame(self.tab2)  #Para dejar espacio entre Tab y Label
        self.f0.pack(fill=X, pady=10)  #-------------------------------

        #---------------------------------------------------------------

        self.lf1 = LabelFrame(self.tab2, text="Datos Titular 1")

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

        self.ccL = Label(self.f4, text='CC:')
        self.ccL.pack(side=LEFT)
        cc1E = Entry(self.f4, textvariable=tit1cc)
        cc1E.pack(side=LEFT, fill=X, expand=1)

        self.nameL = Label(self.f4, text='Nombres:')
        self.nameL.pack(side=LEFT)
        name1E = Entry(self.f4, textvariable=tit1nombres)
        name1E.pack(side=LEFT, fill=X, expand=1)
        name1E.bind("<KeyRelease>", caps)

        self.f5 = Frame(self.lf1)
        self.f5.pack(fill=X)  #-------------------------------------------

        self.tbancpL = Label(self.f5, text='Banco:')
        self.tbancpL.pack(side=LEFT)
        bank1Cbx = Combobox(self.f5,
                            textvariable=tit1banco,
                            values=tbancos,
                            width=12)
        bank1Cbx.set('')
        bank1Cbx.pack(side=LEFT)

        self.tbancpL = Label(self.f5, text='Tipo Cuenta:')
        self.tbancpL.pack(side=LEFT)
        tbank1Cbx = Combobox(self.f5,
                             textvariable=tit1tcuenta,
                             values=tbanktype,
                             width=8)
        tbank1Cbx.set('')
        tbank1Cbx.pack(side=LEFT)

        self.tcuentaL = Label(self.f5, text='# Cuenta:')
        self.tcuentaL.pack(side=LEFT)
        tcuenta1E = Entry(self.f5, textvariable=tit1numcuenta)
        tcuenta1E.pack(side=LEFT, fill=X, expand=1)

        self.lf1.pack(fill=X, ipady=5)  #================================

        self.f0 = Frame(self.tab2)  #Para dejar espacio entre Tab y Label
        self.f0.pack(fill=X, pady=10)  #-------------------------------

        #---------------------------------------------------------------

        self.lf2 = LabelFrame(self.tab2, text="Datos Titular 2")

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

        self.ccL = Label(self.f5, text='CC:')
        self.ccL.pack(side=LEFT)
        cc2E = Entry(self.f5, textvariable=tit2cc)
        cc2E.pack(side=LEFT, fill=X, expand=1)

        self.nameL = Label(self.f5, text='Nombres:')
        self.nameL.pack(side=LEFT)
        name2E = Entry(self.f5, textvariable=tit2nombres)
        name2E.pack(side=LEFT, fill=X, expand=1)
        name2E.bind("<KeyRelease>", caps)

        self.f6 = Frame(self.lf2)
        self.f6.pack(fill=X)  #-------------------------------------------

        self.tbancpL = Label(self.f6, text='Banco:')
        self.tbancpL.pack(side=LEFT)
        bank2Cbx = Combobox(self.f6,
                            textvariable=tit2banco,
                            values=tbancos,
                            width=12)
        bank2Cbx.set('')
        bank2Cbx.pack(side=LEFT)

        self.tbancpL = Label(self.f6, text='Tipo Cuenta:')
        self.tbancpL.pack(side=LEFT)
        tbank2Cbx = Combobox(self.f6,
                             textvariable=tit2tcuenta,
                             values=tbanktype,
                             width=8)
        tbank2Cbx.set('')
        tbank2Cbx.pack(side=LEFT)

        self.tcuentaL = Label(self.f6, text='# Cuenta:')
        self.tcuentaL.pack(side=LEFT)
        tcuenta2E = Entry(self.f6, textvariable=tit2numcuenta)
        tcuenta2E.pack(side=LEFT, fill=X, expand=1)

        self.lf2.pack(fill=X, ipady=5)  #================================

        #---------------------------------------------------------------

        self.nb.add(self.tab1, text="Personales")
        self.nb.add(self.tab2, text="Complementarios")

        self.nb.pack()

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

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

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

        update = Button(self.btns,
                        text='Actualizar',
                        bg='navy',
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=actualizar,
                        state=DISABLED)
        update.pack(side=RIGHT)

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

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

        self.aside = Frame(self)
        self.aside.pack(side=LEFT, fill=BOTH, expand=True)

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

        self.viewer = Label(self.wrap1, text="LISTA DE PROPIETARIOS")
        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,
                     bg='#d8ecf3')
        scroll.config(command=lb.yview)
        lb.pack(fill=BOTH)
        lb.bind("<Double-Button-1>", callback)
        lb.bind("<Button-3>", popup)
        #lb.bind('<Escape>', release)

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

        self.updateBP = Button(self.wrap2,
                               text='Cargar lista',
                               width=20,
                               bg='navy',
                               foreground='white',
                               activebackground='red3',
                               activeforeground='white',
                               command=cargar_lista)
        self.updateBP.pack()

        delete = Button(self.wrap2,
                        text='Borrar',
                        bg='navy',
                        width=20,
                        foreground='white',
                        activebackground='red3',
                        activeforeground='white',
                        command=borrar)
        delete.pack()

        edit = Button(self.wrap2,
                      text='Modificar',
                      bg='navy',
                      width=20,
                      foreground='white',
                      activebackground='red3',
                      activeforeground='white',
                      command=modificar)
        edit.pack()

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

        buscador = Label(self.wrap3, text="Buscar por:")
        buscador.pack(side=LEFT)

        R1 = Radiobutton(self.wrap3, text="CC", variable=info, value=1)
        R1.pack(side=LEFT)
        R2 = Radiobutton(self.wrap3, text="Apellido", variable=info, value=2)
        R2.pack(side=LEFT)
        info.set(1)

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

        E = Entry(self.wrap4, textvariable=busqueda, width=24)
        E.pack()
        E.bind("<KeyRelease>", caps)
Beispiel #38
0
class CustomerFrame(Frame):
    def __init__(self, master, customers, output_text, refresh):
        Frame.__init__(self, master)
        self.output_text = output_text
        self.refresh = refresh
        self.root = master
        self.customers = customers

        self.name = StringVar() #edit customer
        self.names = []
        self.ncd = NewCustomerDialog(self.root, self.customers, self.refresh, edit=True)

        self.fname = StringVar()
        self.lname = StringVar()
        self.mname = StringVar()
        self.payment = StringVar()
        self.date = StringVar()
        self.iconname="New Customer"

        lf = LabelFrame(self, text="New Customer")
        lf.grid(padx=5,pady=5,row=0,column=0,sticky='ew')
        
        ### dialog content        
        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',padx=(10,0),pady=(10,2))
        Label(lf, text="Type: ").grid(row=1,sticky='e',pady=2,padx=(10,0))
        Label(lf, text="Date: ").grid(row=1,column=2,sticky='e',ipady=2,padx=(10,0))

        self.fname_en = Entry(lf, width=20, textvariable=self.fname)
        self.mname_en = Entry(lf, width=4, textvariable=self.mname)
        self.lname_en = Entry(lf, width=20, textvariable=self.lname)
        self.payment_cb = Combobox(lf, textvariable=self.payment, width=12,
                                   values=("Drop In", "Punch Card", "Monthly", "Inactive"))
        self.date_en = Entry(lf, width=15, textvariable=self.date)
        
        self.fname_en.grid(row=0,column=1,sticky='ew',pady=(10,2))
        self.mname_en.grid(row=0,column=2,sticky='ew',pady=(10,2))
        self.lname_en.grid(row=0,column=3,sticky='ew',padx=(0,10),pady=(10,2))
        self.payment_cb.grid(row=1,column=1,sticky='ew')
        self.date_en.grid(row=1,column=3,columnspan=2,sticky='ew',padx=(0,10))
        
        ### buttons
        Button(lf, text='Reset Values', width=15,
               command=self.reset_values).grid(row=3,column=0,columnspan=2,sticky='ew',padx=10,pady=(2,10))
        Button(lf, text='Submit', width=15,
               command=self.add_customer).grid(row=3,column=3,sticky='ew',padx=(0,10),pady=(2,10))

        for i in range(4):
            lf.columnconfigure(i, weight=1)

        # edit customer
        lf = LabelFrame(self, text="Edit Customer")
        lf.grid(padx=5,pady=5,row=1,column=0,sticky='ew')

        Label(lf, text="Name: ").grid(row=0,column=0,sticky='e',pady=10,padx=(10,0))
        self.name_cb = Combobox(lf, textvariable=self.name, width=30, values=self.names)
        self.name_cb.grid(row=0,column=1,sticky='ew',pady=10)
        Button(lf, text="Edit",width=15,command=self.edit).grid(row=0,column=2,sticky='ew',padx=10,pady=10)

        for i in range(3):
            lf.columnconfigure(i,weight=1)
        self.columnconfigure(0,weight=1)

        self.fname_en.focus_set() #cursor goes here when frame is created
        self.update_names()
        self.reset_values() #zero out all values in new customer

    def edit(self):
        old_name = str(self.name.get())
        parsed = old_name.split(' ',2)
        (line,row) = self.customers.find(parsed[2],parsed[0],parsed[1])
        
        self.ncd.show(line)
        self.refresh() #refresh the global refresh
        name = ' '.join([self.ncd.fname.get(),self.ncd.mname.get(),self.ncd.lname.get()])
        self.output_text("+ - Modified: " + old_name + ' (' + line[3] + ') -> ' + name + " (" + self.ncd.payment.get() + ")\n")

    def update_names(self):
        '''
        update names in edit Combobox
        '''
        self.populate_names()
        if len(self.names) == 0: self.names = ['']
        self.name_cb['values'] = self.names
        self.name_cb.current(0)

    def populate_names(self):
        try:
            clist = self.customers.get_list()
        except IOError:
            self.output_text("! - " + self.customers.filename + " open in another application.\n")
            return
        clist.sort(key = lambda x: ', '.join(x[0:3]).lower())
        self.names = []
        for line in clist:
            self.names.append(' '.join([line[1],line[2],line[0]]))

    def reset_values(self):
        self.fname.set('')
        self.mname.set('')
        self.lname.set('')
        # blow out the field every time this is created
        self.date.set(date.today().strftime("%m/%d/%Y"))
        self.payment_cb.set("Drop In")

    def add_customer(self, event=None):
        # validate and show errors
        if self.fname.get() == '':
            showerror("Error!", "First name field blank!")
        elif self.lname.get() == '':
            showerror("Error!", "Last name field blank!")
        elif self.mname.get() == '':
            showerror("Error!", "Middle initial field blank!")
        elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"):
            showerror("Error!", "Incorect Customer type!")
        elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()):
            showerror("Error!", "Bad entry for date, use format mm/dd/yyyy")
        else:
            # do work
            name = ' '.join([self.fname.get(),self.mname.get(),self.lname.get()])
            old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(),
                                           str(self.mname.get()).strip())
            new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(),
                   str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")]
            
            if not old: #add customer
                self.customers.add(new)
                self.output_text("+ - New Customer: " + name + " (" + self.payment.get() + ")\n")
                self.refresh()
            else:
                var = IntVar()
                
                diag = AlreadyExistsDialog(self.root, new, old, var)
                diag.show()
                if var.get() == 0: # edit
                    pass
                if var.get() == 1: # replace customer
                    self.customers.replace(row, new)
                    self.output_text("+ - Modified: " + name + " (" + self.payment.get() + ")\n")
                    self.refresh()
Beispiel #39
0
class Example(Frame):
    counter = 0

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def nuevoVoluntario(self, nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id):
        global cnx
        cursor = cnx.cursor()
        if estado:
            query = (
                "INSERT INTO caritas.voluntario (nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento) VALUES ('%s','%s','%s','%s','%s','%d','%d','%d','%d','%s','%s','%s','%s')" % (
                    nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id,
                    proyecto_id,
                    telefono_1, telefono_2, genero, fecha_nacimiento))
        else:
            query = (
                "UPDATE caritas.voluntario SET nombre = ('%s'), apellidos = ('%s'), dni = ('%s'), direccion = ('%s'), correo_electronico = ('%s'), localidad_id = ('%d'), estudio_id = ('%d'), parroquial_id = ('%d'),proyecto_id = ('%d'), telefono_1 = ('%s'), telefono_2 = ('%s'), genero = ('%s'), fecha_nacimiento = ('%s') WHERE id = ('%d')"
                % ( nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id, parroquial_id,proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,id))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        t.destroy()

    def getEstudios(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM estudio e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoEstudios = [strings, valores]

    def getParroquial(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM parroquial e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoParroquial = [strings, valores]

    def getPais(self):
        global cnx
        cursor = cnx.cursor(dictionary=True)
        query = ("SELECT * FROM pais e")
        cursor.execute(query)
        valores = []
        strings = []
        for row in cursor:
            valores.append(row['id'])
            strings.append(row['nombre'])

        cursor.close()
        self.listadoPais = [strings, valores]

    def nuevoEstudio(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaEstudios(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarEstudios(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def nuevoPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def nuevaParroquia(self):
        t = Toplevel(self)
        t.wm_title("Parroquial")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaParroquia(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarEstudio(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorEstudios.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorEstudios.get()


        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarEstudio(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarEstudios(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorPais.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorPais.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarPais(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def editarParroquia(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorParroquial.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorParroquial.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)

    def actualizarPais(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.pais SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def actualizarEstudio(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.estudio SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def actualizarParroquia(self, nombreOld, nombreN, t):
        global cnx
        cursor = cnx.cursor()
        query = ("UPDATE caritas.parroquial SET nombre= ('%s') WHERE nombre = ('%s')" % (nombreN, nombreOld))
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def BorrarEstudios(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.estudio WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def BorrarPais(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.pais WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def BorrarParroquial(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("DELETE FROM caritas.parroquial WHERE nombre = ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def nuevaEntradaEstudios(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.estudio (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getEstudios()
        self.selectorEstudios['values'] = self.listadoEstudios[0]

        t.destroy()

    def nuevaEntradaPais(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.pais (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getPais()
        self.selectorPais['values'] = self.listadoPais[0]

        t.destroy()

    def nuevaEntradaParroquia(self, nombre, t):
        global cnx
        cursor = cnx.cursor()
        query = ("INSERT INTO caritas.parroquial (nombre) VALUE ('%s')" % nombre)
        cursor.execute(query)
        cnx.commit()
        cursor.close()

        self.getParroquial()
        self.selectorParroquial['values'] = self.listadoParroquial[0]

        t.destroy()

    def ventanaVoluntarios(self,row):

        id = -1
        guardar = TRUE
        # Creamos una ventana nueva
        t = Toplevel(self)
        t.wm_title("Crear Voluntario")

        # Etiqueta y entrada de nombre
        Label(t, text="Nombre").grid(row=0)
        entradaNombre = Entry(t)
        entradaNombre.grid(row=0, column=1,sticky = "ew")

        # Etiqueta y entrada de apellidos
        Label(t, text="Apellidos").grid(row=1)
        entradaApellidos = Entry(t)
        entradaApellidos.grid(row=1, column=1,sticky = "ew")

        # Etiqueta y entrada de DNI
        Label(t, text="DNI").grid(row=2)
        entradaDNI = Entry(t)
        entradaDNI.grid(row=2, column=1,sticky = "ew")

        # Etiqueta y entrada de Dirreccion
        Label(t, text="Direccion").grid(row=3)
        entradaDireccion = Entry(t)
        entradaDireccion.grid(row=3, column=1)

        # Etiqueta y seleccion de Estudios
        Label(t, text="Estudios").grid(row=4)
        box_value = StringVar()
        self.getEstudios()
        self.selectorEstudios = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorEstudios['values'] = self.listadoEstudios[0]
        self.selectorEstudios.configure(width=25)
        self.selectorEstudios.current(0)
        self.selectorEstudios.grid(row=4, column=1)

        botonEditarEstudios = Button(t, text="Editar", command=self.editarEstudio)
        botonNuevosEstudios = Button(t, text="Nuevo", command=self.nuevoEstudio)
        botonEditarEstudios.grid(row=4, column=2)
        botonNuevosEstudios.grid(row=4, column=3)

        # Etiqueta y seleccion de Genero
        Label(t, text="Genero").grid(row=5)
        seleccionGenero = Combobox(t, values=["Masculino (M)", "Femenino (F)"], state='readonly')
        seleccionGenero.grid(row=5, column=1)

        # Etiqueta y seleccion de Parroquial
        Label(t, text="Parroquial").grid(row=6)
        box_value = StringVar()
        self.getParroquial()
        self.selectorParroquial = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorParroquial['values'] = self.listadoParroquial[0]
        self.selectorParroquial.configure(width=25)
        self.selectorParroquial.current(0)
        self.selectorParroquial.grid(row=6, column=1)

        botonEditarParroquial = Button(t, text="Editar", command=self.editarParroquia)
        botonNuevaParroqual = Button(t, text="Nuevo", command=self.nuevaParroquia)
        botonEditarParroquial.grid(row=6, column=2)
        botonNuevaParroqual.grid(row=6, column=3)

        # Etiqueta y seleccion de Correo
        Label(t, text="Correo").grid(row=0, column=4)
        entradaCorreo = Entry(t)
        entradaCorreo.grid(row=0, column=5)

        Label(t, text="Telefono 1").grid(row=1, column=4)
        entradaTelefono1 = Entry(t)
        entradaTelefono1.grid(row=1, column=5)

        Label(t, text="Telefono 2").grid(row=2, column=4)
        entradaTelefono2 = Entry(t)
        entradaTelefono2.grid(row=2, column=5)

        # Etiqueta y entrada de Fecha
        Label(t, text="Fecha").grid(row=3, column=4)
        entradaAno = Entry(t)
        entradaMes = Entry(t)
        entradaDia = Entry(t)
        entradaAno.grid(row=3, column=5)
        entradaMes.grid(row=3, column=6)
        entradaDia.grid(row=3, column=7)

        # Etiqueta y seleccion de Pais
        Label(t, text="Pais").grid(row=4, column=4)
        box_value = StringVar()
        self.getPais()
        self.selectorPais = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorPais['values'] = self.listadoPais[0]
        self.selectorPais.configure(width=25)
        self.selectorPais.current(0)
        self.selectorPais.grid(row=4, column=5)

        botonEditarPais = Button(t, text="Editar", command=self.editarPais)
        botonNuevaPais = Button(t, text="Nuevo", command=self.nuevoPais)
        botonEditarPais.grid(row=4, column=6)
        botonNuevaPais.grid(row=4, column=7)

        #Rellenamos los cambos si estamos editando
        if row > -1:
            voluntario = self.table.model.getRecordAtRow(row)
            entradaNombre.insert(END,voluntario['nombre'])
            entradaApellidos.insert(END,voluntario['apellidos'])
            entradaCorreo.insert(END,voluntario['correo_electronico'])
            entradaTelefono1.insert(END,voluntario['telefono_1'])
            entradaTelefono2.insert(END,voluntario['telefono_2'])
            entradaDireccion.insert(END,voluntario['direccion'])
            entradaDNI.insert(END,voluntario['dni'])
            self.selectorEstudios.set(voluntario['estudio'])
            self.selectorParroquial.set(voluntario['parroquial'])
            guardar = FALSE
            id = voluntario['id']





        button5 = Button(t, text="Guardar", command=lambda: self.nuevoVoluntario(entradaNombre.get(),
                                                                                 entradaApellidos.get(),entradaDNI.get(),entradaDireccion.get(),
                                                                                 entradaCorreo.get(),1,self.listadoEstudios[1][self.selectorEstudios.current()],
                                                                                 self.listadoParroquial[1][self.selectorParroquial.current()],
                                                                                 1,entradaTelefono1.get(),entradaTelefono2.get(),"M","2001-01-01",t,guardar,id))
        button6 = Button(t, text="Cancelar", command=t.destroy)

        button5.grid(row=7, column=4)
        button6.grid(row=7, column=5)


    def validarVoluntario(self, nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id):

        guarda = True
        error = ""

        if len(nombre)<3 :
            error = error + "Nombre debe tener mas de 2 caracteres\n"
            guarda = False

        if len(apellidos)<3 :
            error = error + "Apellidos debe tener mas de 2 caracteres\n"
            guarda = False

        if len(dni)==9 and dni[8].isalpha() and dni[0-7].isdigit():
            error = error + "Dni tiene el formato NNNNNNNNX donde N es un digito y X una letra \n"
            guarda = False

        if len(direccion)==0:
            error = error + "Introduzca una Dirección \n"
            guarda = False

        if len(correo_electronico)<5:
            error = error + "Introduzca una dirección de correo valida \n"
            guarda = False


        if len(telefono_1)<9:
            error = error + "Introduzca un numero valido \n"
            guarda = False

        if len(telefono_1)==0:
            telefono_1=0

        if guarda:self.nuevoVoluntario(nombre, apellidos, dni, direccion, correo_electronico, localidad_id, estudio_id,
                        parroquial_id, proyecto_id, telefono_1, telefono_2, genero, fecha_nacimiento,t,estado,id)
        # añadir el error
        else:
            print error

    def ventanaImprimir(self):
        t = Toplevel(self)
        t.wm_title("Imprimir")

        Label(t, text="Numero de Copias por etiqueta").pack()
        w = Spinbox(t, from_=1, to=10)
        w.pack()

        buttonImprimir = Button(t, text="Imprimir",  command=lambda:self.imprimir(int(w.get()),t))
        buttonImprimir.pack()

    def agregarListado(self,numero):
        voluntario = self.table.model.getRecordAtRow(numero)
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        arrayListado = self.selectTable.getModel().data
        valores = {}
        i=1
        for values in arrayListado:
            valores['row',i]=arrayListado['row',i]
            i+=1
        valores['row',i]=voluntario
        modelNuevo.importDict(valores)

        self.selectTable.updateModel(modelNuevo)
        self.selectTable.redrawTable()

    def quitarListado(self,numero):
        voluntario = self.selectTable.model.getRecordAtRow(numero)
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        print numero

        arrayListado = self.selectTable.getModel().data
        valores = {}
        i=1
        for values in arrayListado:
            if numero+1 != i:
                valores['row',i]=arrayListado['row',i]
            i+=1
        modelNuevo.importDict(valores)

        self.selectTable.updateModel(modelNuevo)
        self.selectTable.redrawTable()

    def imprimir(self,numero,label):
        pdf = fpdf.FPDF(format='letter')
        pdf.add_page()
        pdf.set_font("Arial", size=14)

        indice=1
        columna=1
        fila=0
        p=0
        for ficha in self.listadoSeleccionado:
            row = self.listadoSeleccionado['row',indice]
            for x in range(0, numero):
                if p==9:
                    pdf.add_page()
                    p=0
                else:
                    p+=1

                texto = 'Nombre: %s\nApellidos: %s\nDireccion: %s\nTelefono: %s' %(row["nombre"],row["apellidos"],row["direccion"],row["telefono_1"])
                pdf.multi_cell(65, 10,texto,align='C')
                pdf.set_xy(70*columna,60*fila +10)
                columna = columna + 1
                if columna == 4:
                    columna=1
                    fila=fila+1
                    pdf.set_xy(10,60*fila +10)

            indice = indice + 1
        pdf.output("tutorial.pdf")

        label.destroy()

    def buscar(self,nombre,apellidos):

        modelCompleto = TableModel()
        modelNuevo = TableModel()

        modelNuevo.addColumn("nombre")
        modelNuevo.addColumn("apellidos")
        modelNuevo.addColumn("dni")
        modelNuevo.addColumn("direccion")
        modelNuevo.addColumn("correo_electronico")
        modelNuevo.addColumn("estudio")
        modelNuevo.addColumn("parroquial")
        modelNuevo.addColumn("proyecto")
        modelNuevo.addColumn("genero")
        modelNuevo.addColumn("fecha_nacimiento")
        modelNuevo.addColumn("telefono_1")
        modelNuevo.addColumn("telefono_2")

        self.listilla= queryAllVoluntarios()
        modelCompleto.importDict(self.listilla)
        searchterms = [('nombre', nombre, 'contains', 'AND'),('apellidos', apellidos, 'contains', 'AND')]
        result=modelCompleto.getDict(modelCompleto.columnNames, filters=searchterms)
        modelNuevo.importDict(result)
        self.listadoSeleccionado = result
        self.table.updateModel(modelNuevo)
        self.table.redrawTable()

    def eventoClic(self):
        print "Clicado"
        return


    def initUI(self):

        self.parent.title("Caritas")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        frameMenu = Frame(self)
        frameMenu.pack(fill="both", expand="0", side=RIGHT)

        labelBusqueda = LabelFrame(frameMenu, text="Busqueda")
        labelBusqueda.pack(fill="x",expand =1)

        labelVoluntarios = LabelFrame(frameMenu)
        labelVoluntarios.pack(fill="both",expand =0)

        frameTabla = Frame(self)
        frameTabla.pack(fill="both", expand="1", side=LEFT)

        labelTabla = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelBotonera = LabelFrame(frameTabla)
        labelTabla.pack(fill="both", expand="1")

        labelSelect = LabelFrame(frameTabla)
        labelSelect.pack(fill="both", expand="1")

        model = TableModel()
        modelSelect = TableModel()

        model.addColumn("nombre")
        model.addColumn("apellidos")
        model.addColumn("dni")
        model.addColumn("direccion")
        model.addColumn("correo_electronico")
        model.addColumn("estudio")
        model.addColumn("parroquial")
        model.addColumn("proyecto")
        model.addColumn("genero")
        model.addColumn("fecha_nacimiento")
        model.addColumn("telefono_1")
        model.addColumn("telefono_2")

        modelSelect.addColumn("nombre")
        modelSelect.addColumn("apellidos")
        modelSelect.addColumn("dni")
        modelSelect.addColumn("direccion")
        modelSelect.addColumn("correo_electronico")
        modelSelect.addColumn("estudio")
        modelSelect.addColumn("parroquial")
        modelSelect.addColumn("proyecto")
        modelSelect.addColumn("genero")
        modelSelect.addColumn("fecha_nacimiento")
        modelSelect.addColumn("telefono_1")
        modelSelect.addColumn("telefono_2")

        #Tabla Voluntarios
        self.listilla= queryAllVoluntarios()
        model.importDict(self.listilla)
        self.table = TableCanvas(labelTabla, model=model,editable=False)
        self.table.createTableFrame()
        self.table.handle_double_click(self.eventoClic)

        #Tabla Seleccionados
        self.selectTable = TableCanvas(labelSelect, model=modelSelect,editable=False)
        self.selectTable.createTableFrame()
        self.listadoSeleccionado = []

        L1 = Label(labelBusqueda, text="Nombre")
        L1.pack()
        E1 = Entry(labelBusqueda)
        E1.pack()

        L2 = Label(labelBusqueda, text="Apellidos")
        L2.pack()
        E2 = Entry(labelBusqueda)
        E2.pack()

        botonArriba = Button(labelVoluntarios, text="Agregar al listado",  command=lambda:self.agregarListado(self.table.getSelectedRow()))
        botonArriba.pack()
        botonAbajo = Button(labelVoluntarios, text="Quitar del listado",  command=lambda:self.quitarListado(self.selectTable.getSelectedRow()))
        botonAbajo.pack()

        button = Button(labelBusqueda, text="Buscar", command=lambda: self.buscar(E1.get(),E2.get()))
        button.pack()

        button = Button(labelVoluntarios, text="Nuevo Voluntario",  command=lambda:self.ventanaVoluntarios(-1))
        button.pack()

        buttonEditar = Button(labelVoluntarios, text="Editar Voluntario",  command=lambda:self.ventanaVoluntarios(self.table.getSelectedRow()))
        buttonEditar.pack()

        buttonImprimir = Button(labelVoluntarios, text="Imprimir",  command=lambda:self.ventanaImprimir())
        buttonImprimir.pack()
Beispiel #40
0
class Window(Tk):
    def __init__(self):
        Tk.__init__(self)

        # Global Elements
        self.main_color = '#333333'
        self.sub_color = '#444444'
        self.the_file = None
        self.upper_list = [
            'SELECT', 'FROM', 'ORDER', 'GROUP', 'BY', 'IS', 'NULL', 'ISNULL',
            'NOTNULL', 'TRUE', 'FALSE', 'JOIN', 'LEFT', 'RIGHT', 'WHERE',
            'HAVING', 'PARTITION', 'OVER', 'WITH', 'AS', 'NOT', 'AND', 'OR',
            'ON', 'IN', 'BETWEEN', 'UNBOUNDED', 'PROCEEDING', 'FOLLOWING',
            'UNION', 'ALL', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'COALESCE',
            'NVL', 'AVG', 'MAX', 'SUM', 'COUNT', 'WITHIN', 'LISTAGG'
        ]
        text_box_font_options = {
            'name': [
                'none', 'Courier', 'Georgia', 'Gothic', 'Impact', 'System',
                'Tahoma', 'Times', 'Verdana'
            ],
            'size': []
        }
        for num in range(6, 101):
            text_box_font_options['size'].append(num)

        # Program attributes
        self.state('zoomed')  # starts maximized
        self.title('Casing Formatter')
        self.config(bg=self.main_color)

        # Frames
        self.main_frame = Frame(self,
                                bg=self.main_color,
                                width=600,
                                height=400)
        self.main_frame.pack(side=TOP, fill=BOTH, expand=TRUE)
        self.button_frame = Frame(self.main_frame, bg=self.main_color)
        self.button_frame.pack(side=LEFT, fill=BOTH)
        self.text_frame = Frame(self.main_frame, bg=self.main_color)
        self.text_frame.pack(
            side=LEFT,
            fill=BOTH,
            expand=TRUE,
        )

        # Scrollbar
        self.text_scrollbar = Scrollbar(self.main_frame)
        self.text_scrollbar.pack(side=RIGHT, fill=BOTH)

        # Buttons
        button_font = 'helvetica 18 bold'
        self.open_file_button = Button(self.button_frame,
                                       text='Open File',
                                       command=self.open_file,
                                       font='helvetica 14',
                                       relief=RAISED,
                                       bg='deepskyblue4',
                                       fg='white')
        self.open_file_button.pack(side=TOP, padx=5, pady=4)
        self.upper_button = Button(self.button_frame,
                                   text='A',
                                   width=3,
                                   command=self.cap_file,
                                   font=button_font,
                                   relief=RAISED,
                                   bg=self.sub_color,
                                   fg='white')
        self.upper_button.pack(side=TOP, padx=5, pady=4)
        self.lower_button = Button(self.button_frame,
                                   text='a',
                                   width=3,
                                   command=self.lower_file,
                                   font=button_font,
                                   relief=RAISED,
                                   bg=self.sub_color,
                                   fg='white')
        self.lower_button.pack(side=TOP, padx=5, pady=4)
        self.semi_lower_button = Button(self.button_frame,
                                        text='Ab',
                                        width=3,
                                        command=self.semi_lower_file,
                                        font=button_font,
                                        relief=RAISED,
                                        bg=self.sub_color,
                                        fg='white')
        self.semi_lower_button.pack(side=TOP, padx=5, pady=4)
        self.semi_lower_button = Button(self.button_frame,
                                        text='Apply Font',
                                        command=self.text_box_font,
                                        font='helvetica 14',
                                        relief=RAISED,
                                        bg=self.sub_color,
                                        fg='white')
        self.semi_lower_button.pack(side=BOTTOM, padx=5, pady=4)

        # Font drop-down menus
        self.font_name_dropdown = Combobox(
            self.button_frame,
            values=text_box_font_options['name'],
            justify='center')
        self.font_name_dropdown.set(text_box_font_options['name'][0])
        self.font_name_dropdown.pack(side=BOTTOM, padx=5, pady=4)
        self.font_style = self.font_name_dropdown.get()

        self.font_size_dropdown = Combobox(
            self.button_frame,
            values=text_box_font_options['size'],
            justify='center')
        self.font_size_dropdown.set(12)
        self.font_size_dropdown.pack(side=BOTTOM, padx=5, pady=4)
        self.text_font_size = self.font_size_dropdown.get()

        # Text boxes
        self.text_box_before = Text(self.text_frame,
                                    relief=SUNKEN,
                                    bg=self.sub_color,
                                    fg='grey',
                                    font=(self.font_style,
                                          self.text_font_size),
                                    wrap=WORD,
                                    yscrollcommand=self.text_scrollbar.set)
        self.text_box_before.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2)
        self.text_box_after = Text(self.text_frame,
                                   relief=SUNKEN,
                                   bg=self.sub_color,
                                   fg='grey',
                                   font=(self.font_style, self.text_font_size),
                                   wrap=WORD,
                                   yscrollcommand=self.text_scrollbar.set)
        self.text_box_after.pack(side=LEFT, fill=BOTH, expand=TRUE, padx=2)
        self.text_scrollbar.config(command=self.yview)

        # Bottom Status bar
        self.status_text = StringVar()
        self.status_text.set('')
        self.status_label = Label(self,
                                  textvariable=self.status_text,
                                  relief=SUNKEN,
                                  font='system 8',
                                  fg='#333333')
        self.status_label.pack(side=BOTTOM, fill=X)

    def yview(self, *args):
        # Used to make both text boxes scroll at the same time
        self.text_box_before.yview(*args)
        self.text_box_after.yview(*args)

    def create_output_file(self):
        # This allows you to choose a directory for the output file
        self.savedir = tkFileDialog.askdirectory(
            title='Select folder to save results')
        if self.savedir != '':
            self.output_file = open(self.savedir + '/' + self.open_file, 'w')
        else:
            self.status_text.set('')
            self.status_label.config(bg='white')

    def cap_file(self):
        if self.the_file != None:
            sql_file = self.the_file.read()
            self.create_output_file()
            self.output_file.write(sql_file.upper())
            self.output_file.close()
            new_sql_file = open(self.savedir + '/' + self.open_file, 'r')

            self.text_box_before.insert(END, sql_file)
            self.text_box_after.insert(END, new_sql_file.read())

            new_sql_file.close()
            self.status_text.set('Saved as: ' + self.open_file)
            self.status_label.config(bg='#777777')

            self.text_color()

    def lower_file(self):
        if self.the_file != None:
            sql_file = self.the_file.read()
            self.create_output_file()
            self.output_file.write(sql_file.lower())
            self.output_file.close()
            new_sql_file = open(self.savedir + '/' + self.open_file, 'r')

            self.text_box_before.insert(END, sql_file)
            self.text_box_after.insert(END, new_sql_file.read())

            new_sql_file.close()
            self.status_text.set('Saved as: ' + self.open_file)
            self.status_label.config(bg='#777777')

            self.text_color()

    def semi_lower_file(self):
        if self.the_file != None:
            sql_file = self.the_file.read()
            temp_split = sql_file.split(' ')
            sql_file_formatted = []
            for item in temp_split:
                for word in re.sub(r'[^A-Za-z0-9._]', '\n', item).split('\n'):
                    if word.upper() in self.upper_list:
                        item = item.replace(word, word.upper())
                    else:
                        item = item.replace(word, word.lower())
                sql_file_formatted.append(item)

            sql_file_formatted = ' '.join(sql_file_formatted)

            self.create_output_file()
            self.output_file.write(sql_file_formatted)
            self.output_file.close()
            new_sql_file = open(self.savedir + '/' + self.open_file, 'r')

            self.text_box_before.insert(END, sql_file)
            self.text_box_after.insert(END, new_sql_file.read())

            new_sql_file.close()
            self.status_text.set('Saved as: ' + self.open_file)
            self.status_label.config(bg='#777777')

            self.text_color()

    def open_file(self):
        self.text_box_before.delete(1.0, END)
        self.text_box_after.delete(1.0, END)
        self.the_file = tkFileDialog.askopenfile(
            parent=self, mode='r', title='Choose a file to format...')
        if self.the_file != None:
            self.open_file = re.sub(
                r'[^A-Za-z0-9._]', '',
                str(self.the_file).split(' ')[2].split('/')[-1])
            self.status_text.set('Selected: ' + self.open_file)
            self.status_label.config(bg='lightblue')
        else:
            self.status_text.set('')
            self.status_label.config(bg='white')
        return self.the_file

    def text_color(self):
        # Colors the words in the before and after text boxes, for the words that are in the upper list
        temp_split = self.text_box_after.get(1.0, END)
        temp_split = temp_split.split('\n')
        line_count = 0
        for line in temp_split:
            line_count += 1
            temp_list = re.sub(r'[^A-Za-z0-9._]', ' ', line).split(' ')
            recon = []
            for item in temp_list:
                recon.append(item)
                letter = len(' '.join(recon))
                if item.upper() in self.upper_list:
                    self.text_box_after.tag_add(
                        "start",
                        str(line_count) + "." + str(letter - len(item)),
                        str(line_count) + "." + str(letter))
                    self.text_box_after.tag_config("start",
                                                   foreground='orange',
                                                   font=(self.font_style,
                                                         self.text_font_size,
                                                         ' bold'))
                    self.text_box_before.tag_add(
                        "start",
                        str(line_count) + "." + str(letter - len(item)),
                        str(line_count) + "." + str(letter))
                    self.text_box_before.tag_config("start",
                                                    foreground='orange',
                                                    font=(self.font_style,
                                                          self.text_font_size,
                                                          ' bold'))

    def text_box_font(self):
        self.text_box_after.tag_add("font", 1.0, END)
        self.text_box_after.tag_config("font",
                                       font=(self.font_name_dropdown.get(),
                                             self.font_size_dropdown.get()))
        self.text_box_before.tag_add("font", 1.0, END)
        self.text_box_before.tag_config("font",
                                        font=(self.font_name_dropdown.get(),
                                              self.font_size_dropdown.get()))
class BoardConfigAdvance(Frame):

    def __init__(self, master=None, main=None):
        Frame.__init__(self, master)

        self.parent = master
        self.main = main

        self.parent.geometry("280x174")
        self.parent.title(os.getenv("NAME") + " - Advance Board Config")
        self.master.configure(padx=10, pady=10)

        self.HEAPSIZE = {"512 byte": 512,
                         "1024 byte": 1024,}
        self.OPTIMIZATION = "-O2 -O3 -Os".split()

        self.mips16_var = IntVar()
        self.checkBox_mips16 = Checkbutton(self.parent, text="Mips16", anchor="w", variable=self.mips16_var)
        self.checkBox_mips16.pack(expand=True, fill=BOTH, side=TOP)

        frame_heap = Frame(self.parent)
        Label(frame_heap, text="Heap size:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True)
        self.comboBox_heapsize = Combobox(frame_heap, values=self.HEAPSIZE.keys())
        self.comboBox_heapsize.pack(fill=X, expand=True, side=RIGHT)
        frame_heap.pack(fill=X, expand=True, side=TOP)

        frame_opt = Frame(self.parent)
        Label(frame_opt, text="Optimization:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True)
        self.comboBox_optimization = Combobox(frame_opt, values=self.OPTIMIZATION)
        self.comboBox_optimization.pack(fill=X, expand=True, side=RIGHT)
        frame_opt.pack(fill=X, expand=True, side=TOP)

        frame_buttons = Frame(self.parent)
        Button(frame_buttons, text="Accept", command=self.accept_config).pack(fill=X, expand=True, side=LEFT)
        Button(frame_buttons, text="Restore Default", command=self.restore_default).pack(fill=X, expand=True, side=RIGHT)
        frame_buttons.pack(fill=X, expand=True, side=BOTTOM)

        self.load_config()


    #----------------------------------------------------------------------
    def quit(self):

        self.master.destroy()



    #----------------------------------------------------------------------
    def load_config(self):

        #Called in the parent frame
        #self.main.configIDE.load_config()

        if self.main.configIDE.config("Board", "mips16", True):
            self.checkBox_mips16.select()
        else:
            self.checkBox_mips16.deselect()

        heapsize = self.main.configIDE.config("Board", "heapsize", 512)
        for key in self.HEAPSIZE.keys():
            if self.HEAPSIZE[key] == heapsize:
                self.comboBox_heapsize.set(key)
                break

        optimization = self.main.configIDE.config("Board", "optimization", "-O3")
        self.comboBox_optimization.set(optimization)


    #----------------------------------------------------------------------
    def restore_default(self):

        self.checkBox_mips16.select()
        self.comboBox_heapsize.set(self.HEAPSIZE.keys()[1])
        self.comboBox_optimization.set(self.OPTIMIZATION[1])


    #----------------------------------------------------------------------
    def accept_config(self):

        self.save_config()
        self.main.configIDE.save_config()
        self.quit()


    #----------------------------------------------------------------------
    def save_config(self):

        self.main.configIDE.set("Board", "mips16", self.mips16_var.get()==1)
        heapsize = self.HEAPSIZE[self.comboBox_heapsize.get()]
        self.main.configIDE.set("Board", "heapsize", heapsize)
        self.main.configIDE.set("Board", "optimization", self.comboBox_optimization.get())
Beispiel #42
0
class Window(Frame):
    def __init__(self, parent, window_type):
        Frame.__init__(self, parent, msg = None)

        self.parent = parent
        if window_type == "main":
            self.initUI_main()
        if window_type == "err":
            self.initUI_err()

    def initUI_main(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(7, weight=1)
        self.columnconfigure(5, pad=10)
        self.columnconfigure(3, pad=10)
        self.columnconfigure(1, weight=3)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=6)


        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W+N, pady=4, padx=5)


        check_box = {"work": IntVar(),
                     "boost": IntVar()}

        check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"])
        check1.grid(row=7, column=0)

        check2 = Checkbutton(self, text="boost games", variable=check_box["boost"])
        check2.grid(row=7, column=1)


        ### old version, may be used again later
        area = Treeview(self)
        area['show'] = 'headings'
        area["columns"] = ("one", "two", "three", "four")
        area.column("one", width=10)
        area.column("two", width=10)
        area.column("three", width=10)
        area.column("four", width=10)
        area.heading("one", text="process name")
        area.heading("two", text="Priority")
        area.heading("three", text="PID")
        area.heading("four", text="Usage")
        ###about this part
        #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N)
        #######

        #comboboxes and relevant buttons

        self.block_drop = Combobox(self, postcommand= self.update_blocked)
        self.block_drop['values'] = working_bans
        self.block_drop.current(0)
        self.block_drop.grid(row=1, column=1, pady=1)
        self.entry = Entry(self)
        self.entry.insert(0, "enter to block")
        self.entry.grid(row=1, column=4)

        block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get()))
        block_btn_remv.grid(row=1, column=2)

        block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"]))
        block_btn_add.grid(row=1, column=3)

        ############
        #boosted combo
        self.boost_drop = Combobox(self, postcommand=self.update_boosted)
        self.boost_drop['values'] = boosted
        self.boost_drop.current(0)
        self.boost_drop.grid(row=2, column=1, pady=1)
        self.entry2 = Entry(self)
        self.entry2.insert(0, "enter to buff priority")
        self.entry2.grid(row=2, column=4, pady=4)

        boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get()))
        boost_btn_remv.grid(row=2, column=2)

        boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"]))
        boost_btn_add.grid(row=2, column=3)

        #########################################

        #degraded combo
        self.deg_drop = Combobox(self, postcommand=self.update_degraded)
        self.deg_drop['values'] = degraded
        self.deg_drop.current(0)
        self.deg_drop.grid(row=3, column=1, pady=1)
        self.entry3 = Entry(self)
        self.entry3.insert(0, "enter to lower priority")
        self.entry3.grid(row=3, column=4, pady=4)

        deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get()))
        deg_btn_remv.grid(row=3, column=2)

        deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"]))
        deg_btn_add.grid(row=3, column=3)

        ####
        #music combo

        self.music_drop = Combobox(self, postcommand=self.update_music)
        self.music_drop['values'] = music_list.keys()
        self.music_drop.current(0)
        self.music_drop.grid(row=4, column=1, pady=1)
        self.entry4 = Entry(self)
        self.entry4.insert(0, "enter url")
        self.entry4.grid(row=4, column=5)
        self.entry5 = Entry(self)
        self.entry5.insert(0, "enter song's name")
        self.entry5.grid(row=4, column=4)

        music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get()))
        music_btn_remv.grid(row=4, column=2)

        music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"]))
        music_btn_add.grid(row=4, column=3)


        abtn = Button(self, text="Activate", command=scan_computer_programs)
        abtn.grid(row=1, column=5, sticky=E)

        sbtn = Button(self, text="Stop", command=lambda: stop_running())
        sbtn.grid(row=2, column=5, pady=6, sticky=E)

        cbtn = Button(self, text="Close", command=quit)
        cbtn.grid(row=3, column=5, pady=4, sticky=E)

        hbtn = Button(self, text="Save", command=save_lists)
        hbtn.grid(row=6, column=0, sticky=W)

        tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py"))
        tsbtn.grid(row=3, column=5, sticky=E)

        obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box))
        obtn.grid(row=6, column=5, sticky=E)

    def initUI_err(self):
        self.parent.title("Personal Helper")
        self.pack(fill=BOTH, expand=True)

    def update_boosted(self):
        self.boost_drop['values'] = boosted
        try:
            self.boost_drop.current(0)
        except:
            self.boost_drop.set("empty")

    def update_blocked(self):
        self.block_drop['values'] = working_bans
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_degraded(self):
        self.deg_drop['values'] = degraded
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")

    def update_music(self):
        self.music_drop['values'] = music_list.keys()
        try:
            self.block_drop.current(0)
        except:
            self.block_drop.set("empty")
Beispiel #43
0
class App(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.levels = list()
        self.signs = list()
        self.items = [i for i in range(0,64)]
        self.items.remove(16)
        self.current_item = 0
        self.parent = parent
        self.max_width = 600
        self.max_height = 600
        self.client = Client()
        self.initDimensions()
        self.initUI()
        self.event = None
        self.reset_canvas()

    def connect(self):

        res = self.client.regis()
        if(res == 1):
            time.sleep(1)
            self.connect_button.config(state = 'disabled')
            self.disconnect_button.config(state = 'normal')

    def disconnect(self):
        self.client.close()
        self.connect_button.config(state = 'normal')
        self.disconnect_button.config(state = 'disabled')


    def initDimensions(self):
        self.canvas_width = self.max_width
        self.canvas_height = self.max_height
        self.rows = 10
        self.cols = 10
        # self.h = 1;
        self.cellwidth = self.canvas_width/self.cols
        self.cellheight = self.canvas_height/self.rows
        self.initData()

    def add_new_level(self):
        temp=dict()
        temp2 = dict()
        self.levels.append(temp)
        self.signs.append(temp2)

    def insert_new_level(self, loc):
        temp=dict()
        temp2 = dict()
        self.levels.insert(loc,temp)
        self.signs.insert(loc,temp2)

    def initData(self):
        self.levels = list()
        self.signs = list()
        self.rect = dict()
        self.rect_text = dict()
        self.curr_level = 0
        self.overlay_level = 0
        self.overlayToggle = False
        self.levels.append(dict())
        self.signs.append(dict())
        self.current_item = 1


    def reset_canvas(self):
        self.canvas.delete(ALL)
        self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols))

    def redraw_overlay(self):
        c = set(self.levels[self.overlay_level].keys())
        if self.overlayToggle == 1:
            for key in c:
                x1 = key[1] * self.cellwidth
                y1 = (self.rows - key[0] - 1) * self.cellheight
                x2 = x1 + self.cellwidth
                y2 = y1 + self.cellheight

                if (key[0], key[1]) in self.rect:
                    self.canvas.itemconfig(self.rect[key[0],key[1]], width = OVERLAYWIDTH)
                else:
                    self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill='white', outline = 'black', width = OVERLAYWIDTH, tag = 'block')
                    self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = '', font=('verdana', 7), tag = 'blocktext')

    def redraw_level(self):
        # self.canvas.delete(ALL)

        # self.rect=dict()
        # self.rect_text = dict()
        start = time.clock()

        b = set(self.levels[self.curr_level].keys())

        for key in b:
            val = self.levels[self.curr_level][key]
            if (key[0], key[1]) in self.rect:
                self.canvas.itemconfig(self.rect[key[0],key[1]], fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH)
                self.canvas.itemconfig(self.rect_text[key[0],key[1]], text = val)
            else:
                x1 = key[1] * self.cellwidth
                y1 = (self.rows - key[0] - 1) * self.cellheight
                x2 = x1 + self.cellwidth
                y2 = y1 + self.cellheight
                self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH, tag = 'block')
                self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = val, font=('verdana', 7), tag = 'blocktext')

        items_to_remove = list()
        for key in self.rect:
            if key not in self.levels[self.curr_level]:
                self.canvas.delete(self.rect[key[0],key[1]])
                self.canvas.delete(self.rect_text[key[0],key[1]])
                items_to_remove.append(key)
        for i in items_to_remove:
            self.rect.pop(i)
            self.rect_text.pop(i)


        self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols))
        self.redraw_overlay()




    def updateDimensions(self,r,c,y=1):
        self.rows = r
        self.cols = c

        self.cellwidth = self.max_width/self.cols
        self.cellheight = self.max_height/self.rows
        if(self.cellwidth<=self.cellheight):
            self.cellheight = self.cellwidth
        else:
            self.cellwidth = self.cellheight
        self.canvas_height = self.rows * self.cellheight
        self.canvas_width = self.cols * self.cellwidth
        self.canvas.config(width = self.canvas_width, height = self.canvas_height)

        self.canvas.delete(ALL)
        self.initData()
        for i in range(y-1):
            self.levels.append(dict())
            self.signs.append(dict())

    def altMenu(self, event):
        # print "Keycode:", event.keycode, "State:", event.keysym, event.type
        self.event = event
        if event.type == '2':
            self.altAction = True
            self.clear_button.config(text = 'Multi Clear', bg = 'white')
            self.delete_button.config(text = 'Multi Delete', bg='white')
            self.insert_button.config(text = 'Multi Insert', bg='white')
            self.copy_level_button.config(text = 'Multi Copy', bg = 'white')
        elif event.type == '3':
            defaultbg = self.parent.cget('bg')
            self.altAction = False
            self.clear_button.config(text = 'Clear Level', bg = defaultbg)
            self.delete_button.config(text = 'Delete', bg = defaultbg)
            self.insert_button.config(text = 'Insert', bg = defaultbg)
            self.copy_level_button.config(text = 'Copy overlay level', bg = defaultbg)
        sys.stdout.flush()

    def initUI(self):

        self.altAction = False
        self.parent.title("Craft Builder")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=0)

        self.columnconfigure(0, pad = 7)
        self.columnconfigure(1, pad = 7)
        self.columnconfigure(2, pad = 7)
        self.columnconfigure(9, weight =1 )
        self.columnconfigure(3, pad=7)
        self.columnconfigure(5, pad=7)

        self.rowconfigure(1, weight=1)
        self.rowconfigure(5, pad=7)
        self.rowconfigure(6, pad=7)
        self.rowconfigure(7, pad=7)
        self.rowconfigure(8, pad=7)

        area = Frame(self, width=500, height=500, borderwidth = 2, relief = 'sunken')
        area.grid(row=1, column=0, columnspan=11, rowspan=4,
            padx=5, sticky=E+W+S+N)

        self.canvas = Canvas(area, bg='white', width=self.canvas_width, height=self.canvas_height)

        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.callbackLeftClick)
        self.canvas.bind("<B1-Motion>", self.callbackLeftClick)
        self.canvas.bind("<Button-3>", self.callbackRightClick)
        self.canvas.bind("<B3-Motion>", self.callbackRightClick)
        self.canvas.bind("<Button-5>", self.scrollWheel)
        self.canvas.bind("<Button-4>", self.scrollWheel)
        self.parent.bind("<Shift_L>", self.altMenu)
        self.parent.bind("<KeyRelease-Shift_L>", self.altMenu)


        self.new_button = Button(self, text="New", command = self.onNew, width = 6)
        self.new_button.grid(row=5, column=0)

        save_button = Button(self, text="Save", command = self.onSave, width = 6)
        save_button.grid(row=6, column=0)

        load_button = Button(self, text="Load", command = self.onLoad, width = 6)
        load_button.grid(row=7, column=0)

        self.connect_button = Button(self, text="Connect", command = self.connect, width = 6)
        self.connect_button.grid(row=8, column=0)

        self.clear_button = Button(self, text="Clear Level", command = self.onClear, width =8)
        self.clear_button.grid(row=5, column=1)

        self.delete_button = Button(self, text="Delete Level", command = self.onDelete, width =8)
        self.delete_button.grid(row=6, column=1)

        self.insert_button = Button(self, text="Insert Level", command = self.onInsertLevel, width =8)
        self.insert_button.grid(row=7, column=1)

        self.disconnect_button = Button(self, text="Disconnect", command = self.disconnect, width = 8)
        self.disconnect_button.grid(row=8, column=1)
        self.disconnect_button['state'] = 'disabled'

        lbl_a = Label(self, text="Curr. Level", font=("Verdana", 10))
        lbl_a.grid(row = 5, column = 2)

        lbl_b = Label(self, text="Overlay Level", font=("Verdana", 10))
        lbl_b.grid(row = 6, column = 2)

        self.copy_level_button = Button(self, text="Copy overlay level", command = self.onCopy, width = 12)
        self.copy_level_button.grid(row=7, column=2, columnspan=1)

        load_world_button = Button(self, text="Load from world", command = self.onLoadFromWorld, width = 12)
        load_world_button.grid(row=8, column=2)

        self.currLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly')
        self.currLevelCombo.grid(row = 5, column = 3)
        self.currLevelCombo.bind("<<ComboboxSelected>>", self.currLevelChooser)
        self.currLevelCombo.set(0)

        self.overlayLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly')
        self.overlayLevelCombo.grid(row = 6, column = 3)
        self.overlayLevelCombo.bind("<<ComboboxSelected>>", self.overlayLevelChooser)
        self.overlayLevelCombo.set(0)


        self.new_level_button = Button(self, text="New Level", command = self.onNewLevel, width = 12)
        self.new_level_button.grid(row=7, column=3,columnspan=1)

        paste_button = Button(self, text="Paste in world", command = self.onPaste, width = 12)
        paste_button.grid(row=8, column=3)

        lbl_d = Label(self, text="Item", font=("Verdana", 10))
        lbl_d.grid(row = 5, column = 4)

        self.toggle = Checkbutton(self, text="Overlay Toggle", command = self.onToggle)
        self.toggle.grid(row=6, column=4)

        rotate_button = Button(self, text="Rotate", command = self.onRotate, width = 12)
        rotate_button.grid(row=7, column=4,columnspan=1)

        paste_sign_button = Button(self, text="Paste Signs", command = self.onPasteSign, width = 12)
        paste_sign_button.grid(row=8, column=4)

        self.itemCombo = Combobox(self, values = self.items, width = 5, state = 'readonly')
        self.itemCombo.grid(row = 5, column = 5)
        self.itemCombo.bind("<<ComboboxSelected>>", self.itemChooser)
        self.itemCombo.set(1)
        self.current_item = 1
        self.lbl_e = Label(self, text="", font=("Verdana", 8), width = 12, relief = 'ridge')
        self.lbl_e.grid(row = 6, column = 5)

        add_geo_button = Button(self, text="Add Geometry", command = self.addGeo, width = 12)
        add_geo_button.grid(row=8, column=5)

        try:
            global builder
            import builder
        except ImportError:
            add_geo_button.config(state = 'disabled')

    def scrollWheel(self, event):
        if event.num == 5:
            #scroll down
            if self.curr_level==len(self.levels) -1:
                pass
            else:
                self.curr_level = self.curr_level + 1
                self.currLevelCombo.set(self.curr_level)
                self.redraw_level()
        else:
            #scroll up
            if self.curr_level == 0:
                pass
            else:
                self.curr_level = self.curr_level - 1
                self.currLevelCombo.set(self.curr_level)
                self.redraw_level()

    def onInsertLevel(self):
        if self.altAction == 1:
            self.w=popupWindow(self,title = "Enter num_levels to insert and level below which to insert\n" +
                                                                 "seperated by a space.")
            self.wait_window(self.w.top)
            self.altAction = 0
            data = self.w.value.split(' ')
            try:
                if len(data) == 2:
                    for i in range(int(data[0])):
                        self.insert_new_level(int(data[1]))
                    self.redraw_level()
                else:
                    print 'Not enough arguments'
            except ValueError:
                print 'Error in values'


        else:
            self.insert_new_level(self.curr_level)
            self.currLevelCombo.config(values = range(len(self.levels)))
            self.overlayLevelCombo.config(values = range(len(self.levels)))
            self.redraw_level()

    def onCopy(self):
        if self.altAction == 1:
            self.w=popupWindow(self,title = "Enter the arguments start_level end_level num_times\n" +
                                                                 "and level above which to copy, all seperated by spaces.")
            self.wait_window(self.w.top)
            self.altAction = 0

            data = self.w.value.split(' ')
            try:
                if len(data) == 4:
                    st,sto = sorted((data[0],data[1]))
                    st = int(st)
                    sto = int(sto)
                    n = data[2]
                    l = int(data[3]) + 1
                    for i in range(int(n)):
                        for j in range(st, sto +1):
                            for col in range(self.cols):
                                for row in range(self.rows):
                                    if (row,col) in self.levels[j]:
                                        if  l+j-st < len(self.levels) :
                                            self.levels[l+j-st][row,col] = self.levels[j][row,col]
                        l = l +(sto-st+1)
                else:
                    print 'Not enough arguments'
            except ValueError:
                print 'Error in values'

        else:
            for col in range(self.cols):
                for row in range(self.rows):
                    if (row,col) in self.levels[self.overlay_level]:
                       self.levels[self.curr_level][row,col] = self.levels[self.overlay_level][row,col]
        sys.stdout.flush()
        self.redraw_level()



    def onClear(self):
        if self.altAction == 1:
            self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to clear\n" +
                                                                 "seperated by a space.")
            self.wait_window(self.w.top)
            self.altAction = 0
            data = self.w.value.split()
            try:
                if len(data) == 2:
                    st,sto = sorted((data[0],data[1]))
                    st = int(st)
                    sto = int(sto)
                    for i in range(st,sto+1):
                        if i < len(self.levels):
                            self.levels[i] = dict()
                            self.signs[i] = dict()
                    self.redraw_level()
                else:
                    print 'Not enough arguments'
            except ValueError:
                print 'Error in values'
        else:
            if tkMessageBox.askquestion('Clear', "Clear Level: " + str(self.curr_level)) == 'yes':
                self.levels[self.curr_level] = dict()
                self.signs[self.curr_level] = dict()
                self.redraw_level()
            else:
                pass

    def onDelete(self):
        if self.altAction == 1:
            self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to delete\n" +
                                                                 "seperated by a space.")
            self.wait_window(self.w.top)
            self.altAction = 0
            data = self.w.value.split()
            try:
                if len(data) == 2:
                    st,sto = sorted((data[0],data[1]))
                    st = int(st)
                    sto = int(sto)
                    for i in range(sto,st-1,-1):
                        if i < len(self.levels) and i >=0 and len(self.levels)>1:
                            self.levels.pop(i)
                            self.signs.pop(i)
                        elif i < len(self.levels) and i ==0 :
                            self.levels[i] = dict()
                            self.signs[i] = dict()

                    self.currLevelCombo.config(values = range(len(self.levels)))
                    self.overlayLevelCombo.config(values = range(len(self.levels)))
                    self.curr_level = 0
                    self.currLevelCombo.set(0)
                    self.overlayLevelCombo.set(0)
                    self.redraw_level()
                else:
                    print 'Not enough arguments'
            except ValueError:
                print 'Error in values'

        else:
            if tkMessageBox.askquestion('Delete', "Delete Level: " + str(self.curr_level)) == 'yes':
                if len(self.levels) == 1:
                    self.onClear()
                else:
                    self.levels.pop(self.curr_level)
                    self.signs.pop(self.curr_level)
                    self.currLevelCombo.config(values = range(len(self.levels)))
                    self.overlayLevelCombo.config(values = range(len(self.levels)))

                    if self.overlayToggle == 1:
                        self.toggle.invoke()
                        self.overlayToggle = 0

                    if self.curr_level != 0:
                        self.curr_level = self.curr_level - 1
                        self.currLevelCombo.set(self.curr_level)
                    else:
                        self.currLevelCombo.set(self.curr_level)
                    self.redraw_level()

    def addGeo(self):
        self.w=popupWindow(self,title = "Enter Command: help for Help")
        self.wait_window(self.w.top)

        try:
            c = self.w.value.split(' ')
            if c[0] == 'help':
                self.h = HelpWindow(self, title = 'Enter command followed by args seperated by spaces\n' +
                                                                    'Available commands (sphere, pyramid, cuboid)\n' +
                                                                    '1.   pyramid x1 x2 y z1 z2 fill(0/1) \n' +
                                                                    '2.   sphere cx cy cz r fill(0/1) \n' +
                                                                    '4.   circle_x x y z r fill(0/1) \n' +
                                                                    '5.   circle_y x y z r fill(0/1) \n' +
                                                                    '6.   circle_z x y z r fill(0/1) \n' +
                                                                    '7.   cylinder_x x1 x2 y z r fill(0/1) \n' +
                                                                    '8.   cylinder_y x y1 y2 z r fill(0/1) \n' +
                                                                    '9.   cylinder_z x y z1 z2 r fill(0/1) \n' +
                                                                    '10. cuboid x1 x2 y1 y2 z1 z2 fill(0/1) \n' )
            elif c[0] == 'sphere':
                if len(c) - 1 == 5:
                    result = builder.sphere(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >=0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item

            elif c[0] == 'pyramid':
                if len(c) - 1 == 6:
                    result = builder.pyramid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item

            elif c[0] == 'circle_x':
                if len(c) - 1 == 5:
                    result = builder.circle_x(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
            elif c[0] == 'circle_y':
                if len(c) - 1 == 5:
                    result = builder.circle_y(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
            elif c[0] == 'circle_z':
                if len(c) - 1 == 5:
                    result = builder.circle_z(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
            elif c[0] == 'cylinder_x':
                if len(c) - 1 == 6:
                    x1,x2 = sorted([int(c[1]),int(c[2])])
                    result = builder.cylinder_x(x1,x2,int(c[3]),int(c[4]),int(c[5]),int(c[6]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
            elif c[0] == 'cylinder_y':
                if len(c) - 1 == 6:
                    y1,y2 = sorted([int(c[2]),int(c[3])])
                    result = builder.cylinder_y(int(c[1]),y1,y2,int(c[4]),int(c[5]),int(c[6]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
            elif c[0] == 'cylinder_z':
                if len(c) - 1 == 6:
                    z1,z2 = sorted([int(c[3]),int(c[4])])
                    result = builder.cylinder_z(int(c[1]),int(c[2]),z1,z2,int(c[5]),int(c[6]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item

            elif c[0] == 'cuboid':
                if len(c) - 1 == 7:
                    result = builder.cuboid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6]),int(c[7]))
                    for i in result:
                        if i[1] < len(self.levels) and i[1] >= 0:
                            if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0:
                                self.levels[i[1]][i[0],i[2]] = self.current_item
                pass

            newLevels = list()
            for i, j in enumerate(self.levels):
                temp = dict()
                for key, val in j.iteritems():
                    if int(val) != 0:
                        temp[key] = val
                newLevels.append(temp)

            self.levels = newLevels

            self.redraw_level()

        except RuntimeError:
            pass

    def onPaste(self):
        self.w=popupWindow(self,title = "On world, facing north (i.e x increases ahead of you,\n"+
                                                            "and z increases to your right.\n" +
                                                            "Enter origin point (x y z) seperated by spaces: eg. 12 12 12:")
        self.wait_window(self.w.top)
        data = self.w.value.split(' ')
        try:
            xo = int(data[0])
            yo = int(data[1])
            zo = int(data[2])
            if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes':
                print 'Pasting'
                count = 0
                for j,i in enumerate(self.levels):
                    for key,value in i.iteritems():
                        xr = int(xo + key[0])
                        yr = int(yo + j)
                        zr = int(zo + key[1])
                        # self.client.client_send(xr,yr,zr,0)
                        if int(value) != 0:
                            self.client.client_send(xr,yr,zr,int(value))
                            count = count + 1
                        if count % NUMPERSEC == 0:
                            time.sleep(1)
            else:
                pass
        except ValueError:
            pass

    def onPasteSign(self):
        self.w=popupWindow(self,title = "Facing north, enter origin point(x y z): eg. 12 12 12:")
        self.wait_window(self.w.top)
        data = self.w.value.split(' ')
        try:
            xo = int(data[0])
            yo = int(data[1])
            zo = int(data[2])
            if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes':
                print 'Pasting'
                count = 0
                for j,i in enumerate(self.signs):
                    for key,value in i.iteritems():
                        xr = int(xo + key[0])
                        yr = int(yo + j)
                        zr = int(zo + key[1])

                        for num,val in enumerate(value):
                            if val!=-1:
                                # print j,i,num, val
                                self.client.client_send_sign(xr, yr, zr, num, val)
                        sys.stdout.flush()
        except ValueError:
            pass

    def onLoadFromWorld(self):
        self.w=popupWindow(self,title = "Enter bottom left point: (x y z)")
        self.wait_window(self.w.top)
        try:
            [x1,y1,z1] = [int(i) for i in self.w.value.split(' ')]

            self.w=popupWindow(self,title = "Enter top right point: (x y z)")
            self.wait_window(self.w.top)
            [x2,y2,z2] = [int(i) for i in self.w.value.split(' ')]

            x1,x2 =  sorted([x1,x2])
            y1,y2 =  sorted([y1,y2])
            z1,z2 =  sorted([z1,z2])

            if tkMessageBox.askquestion('Coords', "Bottom left: " + str(x1) +',' +str(y1) + ',' + str(z1) + '\n' + \
                "Top right: " + str(x2) +',' +str(y2) + ',' + str(z2)) == 'yes':
                print 'Copying',x1,y1,z1,' to',x2,y2,z2
                data = self.client.read_db(x1,y1,z1,x2,y2,z2, db_name)
                signs = self.client.read_signs(x1,y1,z1,x2,y2,z2, db_name)
                newData = list()

                for i in data:
                    temp = dict()
                    for key,value in i.iteritems():
                        if value != 0:
                            temp[key[0], key[1]] = value
                    newData.append(temp)

                newSignData = list()
                for i in signs:
                    temp = dict()
                    for key,value in i.iteritems():
                        temp[key[0], key[1]] = value
                    newSignData.append(temp)

                if self.overlayToggle == 1:
                    self.toggle.invoke()
                    self.overlayToggle = 0
                self.updateDimensions(x2-x1+1, z2-z1+1, len(newData))
                self.reset_canvas()
                self.levels = newData
                self.signs = newSignData
                sys.stdout.flush()

                self.redraw_level()
                self.currLevelCombo.config(values = range(len(self.levels)))
                self.overlayLevelCombo.config(values = range(len(self.levels)))
        except ValueError:
            pass

    def onSave(self):
        filename = asksaveasfilename(parent=self)
        pickle.dump({'Dimensions' : [self.rows,self.cols,len(self.levels)],'Levels' : self.levels, 'Signs' : self.signs}, open(filename, 'wb'))

    def onLoad(self):
        if self.overlayToggle == 1:
            self.toggle.invoke()
            self.overlayToggle = 0

        filename = askopenfilename(parent=self)
        try:
            obj = pickle.load(open(filename, 'rb'))
            self.updateDimensions(int(obj['Dimensions'][0]), int(obj['Dimensions'][1]), int(obj['Dimensions'][2]))
            self.reset_canvas()
            self.levels = obj['Levels']

            if 'Signs' in obj:
                self.signs = obj['Signs']
            self.redraw_level()
            self.currLevelCombo.config(values = range(len(self.levels)))
            self.overlayLevelCombo.config(values = range(len(self.levels)))
        except IOError:
            pass

    def onToggle(self):
        if self.overlayToggle == 0:
            self.overlayToggle =1
            self.redraw_level()
        else:
            self.overlayToggle = 0
            self.redraw_level()

    def onNewLevel(self):
        self.add_new_level()
        self.currLevelCombo.config(values = range(len(self.levels)))
        self.overlayLevelCombo.config(values = range(len(self.levels)))
        self.redraw_level()

    def onRotate(self):
        self.rotatedData = list()
        self.rotatedSignData = list()

        for i in self.levels:
            temp = dict()
            for key,value in i.iteritems():
                xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90)))
                zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90)))
                temp[int(math.floor(xr)),int(math.floor(zr))] = value
            self.rotatedData.append(temp)

        sign_map = {0:2, 3:0, 1:3, 2:1, 6:5, 7:6, 4:7, 5:4} #FOR ROTATION CALCULATION
        for i in self.signs:
            temp = dict()
            for key,value in i.iteritems():
                xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90)))
                zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90)))
                new_value = [value[sign_map[0]],
                                      value[sign_map[1]],
                                      value[sign_map[2]],
                                      value[sign_map[3]],
                                      value[sign_map[4]],
                                      value[sign_map[5]],
                                      value[sign_map[6]],
                                      value[sign_map[7]]]
                temp[int(math.floor(xr)),int(math.floor(zr))] = new_value
            self.rotatedSignData.append(temp)

        #Moving to origin x,z : 0,0
        self.newData=list()
        self.newSignData=list()
        for i in self.rotatedData:
            temp=dict()
            for key,value in i.iteritems():
                temp[key[0], int(key[1])+int((self.rows-1))] = value
            self.newData.append(temp)
        for i in self.rotatedSignData:
            temp=dict()
            for key,value in i.iteritems():
                temp[key[0], int(key[1])+int((self.rows-1))] = value
            self.newSignData.append(temp)


        temp = self.rows
        self.rows = self.cols
        self.cols = temp

        temp = self.curr_level
        temp2 = self.overlay_level
        temp3 = self.overlayToggle
        temp4 = self.current_item

        self.updateDimensions(self.rows, self.cols,len(self.newData))
        self.reset_canvas()
        self.levels = self.newData
        self.signs = self.newSignData
        self.curr_level = temp
        self.overlay_level = temp2
        self.overlayToggle = temp3

        self.itemCombo.set(temp4)
        self.currLevelCombo.config(values = range(len(self.levels)))
        self.overlayLevelCombo.config(values = range(len(self.levels)))
        self.currLevelCombo.set(self.curr_level)
        self.overlayLevelCombo.set(self.overlay_level)
        self.redraw_level()


    def onNew(self):
        if self.overlayToggle == 1:
            self.toggle.invoke()
            self.overlayToggle = 0
        self.w=popupWindow(self,title = "Enter Dimensions in XxZxY format (e.g. 10x20x3)")
        self.wait_window(self.w.top)
        try:
            data = self.w.value.split('x')
            if len(data) == 2:
                self.updateDimensions(int(data[0]), int(data[1]),1)
            else:
                self.updateDimensions(int(data[0]), int(data[1]),int(data[2]))
            # self.initData()
            self.reset_canvas()
            self.currLevelCombo.config(values = range(len(self.levels)))
            self.overlayLevelCombo.config(values = range(len(self.levels)))
        except ValueError:
            pass

    def currLevelChooser(self, event):
        self.curr_level = int(self.currLevelCombo.get())
        self.redraw_level()

    def overlayLevelChooser(self, event):
        self.overlay_level = int(self.overlayLevelCombo.get())
        self.redraw_level()

    def itemChooser(self, event):
        self.current_item = int(self.itemCombo.get())

    def callbackLeftClick(self,event):
        if self.current_item == 0:
            return
        col = int(math.floor((event.x)/self.cellwidth))
        row = int(math.floor((event.y)/self.cellheight))
        x1 = col * self.cellwidth
        y1 = row * self.cellheight
        x2 = x1 + self.cellwidth
        y2 = y1 + self.cellheight

        if (self.rows - row - 1,col) in self.rect:
            self.canvas.itemconfig(self.rect[self.rows - row - 1,col],fill=COLORS[self.current_item])
            self.canvas.itemconfig(self.rect_text[self.rows - row - 1,col], text = str(self.current_item))
        else:
            self.rect[self.rows - row - 1,col] = self.canvas.create_rectangle(x1,y1,x2,y2, fill=COLORS[self.current_item], outline = 'black', width = DEFAULTWIDTH, tag = 'block')
            self.rect_text[self.rows - row - 1,col] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = self.current_item, font=('verdana', 7), tag = 'blocktext')

        self.levels[self.curr_level][self.rows - row - 1,col] = self.current_item

        if row < self.rows and row >=0 and col < self.cols and col >= 0:
            self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col))

    def callbackRightClick(self,event):
        col = int(math.floor((event.x)/self.cellwidth))
        row = int(math.floor((event.y)/self.cellheight))

        if (self.rows - row - 1,col) in self.rect:
            self.canvas.delete(self.rect[self.rows - row - 1,col])
            self.canvas.delete(self.rect_text[self.rows - row - 1,col])
            self.rect.pop((self.rows - row -1, col))
            self.rect_text.pop((self.rows - row -1, col))

        self.levels[self.curr_level].pop((self.rows - row - 1,col),None)

        if row < self.rows and row >=0 and col < self.cols and col >= 0:
            self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col))
Beispiel #44
0
class Admindocs(Frame):
        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)#<--------------------------------------
# Create Generator Type Dropdown Widgets
GenType_lbl = Label(root,
                    text="Choose Generator Type: ",
                    fg=textcol,
                    bg=bgColor)
GenType_lbl.place(x=20, y=20, height=20)
GenType_tlt = CreateToolTip(GenType_lbl,
                            "Choose what type of noise generator to use")

GenType_dpd = Combobox(root,
                       values=GenTypeOptions,
                       textvariable=GenVar,
                       takefocus=True,
                       state="readonly")
GenType_dpd.set(GenTypeOptions[3])
GenType_dpd.place(x=170, y=20, height=20)

#Create Gridsize Entry Widget

Grid_lbl = Label(root, text="GridSize:", fg=textcol, bg=bgColor)
Grid_lbl.place(x=20, y=50, height=20)

Grid_tlt = CreateToolTip(
    Grid_lbl,
    "Use values no lower than 2. High values take longer to generate, and cost more memory."
)

gridx_lbl = Label(root, text="X:", fg=textcol, bg=bgColor)
gridx_lbl.place(x=80, y=50, height=20, width=40)
grids_x = Entry(root, bg=bgColor, fg=textcol)