示例#1
0
class App(Frame):
    """Basic test frame for the table"""
    data = {}
    table = TableCanvas

    def __init__(self, parent=None):

        self.table = TableCanvas
        self.parent = parent
        Frame.__init__(self)
        self.main = self.master
        self.main.title('Test')
        # Initialize frame for the table
        #f = Frame(self.main)

        # Initialize the grid location of the table
        #f.grid(row=0, column=1, sticky="nsew")

        # no need to pack since we using grid geometry
        # f.pack(fill=tk.Y,expand=-1,side = tk.LEFT)

        # Create/Format table
        #table = TableCanvas(f, cellwidth=60, data = test, cellbackgr='white', thefont=('Arial',12),rowheight=25, rowheaderwidth=30, rowselectedcolor='yellow', editable=True)

        #Import table from csv
        #table.importCSV('2017_Traffic_Volume_Flow.csv')
        """if importing table as dictionary, use this: data is of type dictionary
        """
        # table = TableCanvas(f, cellwidth=60, data = data, cellbackgr='white',
        #                    thefont=('Arial', 12), rowheight=25, rowheaderwidth=30,
        #                    rowselectedcolor='yellow', editable=True)

        #print (table.model.columnNames)
        #table.show()
        # sort the first column from highest to lowest (the sum of incident column)
        # table.sortTable(reverse=1)

        return

    def importData(self, dataImport):
        data = dataImport
        model = TableModel()
        model.importDict(data)
        f = Frame(self.main)
        self.table = TableCanvas(f,
                                 model,
                                 cellwidth=60,
                                 cellbackgr='white',
                                 thefont=('Arial', 12),
                                 rowheight=25,
                                 rowheaderwidth=30,
                                 rowselectedcolor='yellow',
                                 editable=True)
        self.table.createTableFrame()
        self.table.show()
        f.grid(row=0, column=1, sticky="nsew")

    def sortData(self, l, c):
        self.table.sortTable(reverse=l, columnIndex=c)
        self.table.redraw()
示例#2
0
class SalariesCalculator():
    def __init__(self, Salaries):
        date_var1 = tk.StringVar()
        date_var2 = tk.StringVar()
        self.Worker = "Francisco"
        self.window = Salaries
        Date = str(date.today().strftime("%d/%m/%Y"))
        if Date[0:2] <= '15':
            D1 = "01" + Date[2:]
            D2 = "15" + Date[2:]
        else:
            D1 = "16" + Date[2:]
            D2 = Date
        X = 50
        Y = 50

        Lb = tk.Label(self.window,
                      bg='skyblue',
                      font=("Arial", 12),
                      text="De:")
        Lb.place(x=X + 80, y=Y)
        self.Date1 = tk.Entry(self.window,
                              bg='white',
                              font=("Arial", 12),
                              textvariable=date_var1)
        date_var1.set(D1)
        self.Date1.place(x=X + 80, y=Y + 30)

        Lb = tk.Label(self.window,
                      bg='skyblue',
                      font=("Arial", 12),
                      text="Hasta:")
        Lb.place(x=X + 80, y=Y + 60)
        self.Date2 = tk.Entry(self.window,
                              bg='white',
                              font=("Arial", 12),
                              textvariable=date_var2)
        date_var2.set(D2)
        self.Date2.place(x=X + 80, y=Y + 90)

        Lb = tk.Label(self.window,
                      bg='skyblue',
                      font=("Arial", 12),
                      text="Concepto:")
        Lb.place(x=X + 335, y=Y)
        self.Worker_list = tk.Listbox(self.window,
                                      bg='white',
                                      fg='black',
                                      height=3,
                                      selectmode='SINGLE',
                                      width=25,
                                      font=("Arial", 12))
        Workers = ['Francisco', 'Guadalupe', 'Diego']
        for item in Workers:
            self.Worker_list.insert(tk.END, item)
        self.Worker_list.place(x=X + 335, y=Y + 30)
        self.Worker_list.bind("<ButtonRelease-1>", self.update_table)

        ###### Tabla de Salarios ######
        Lb = tk.Label(self.window,
                      bg='skyblue',
                      font=("Arial", 12),
                      text="Salarios:")
        Lb.place(x=X + 663, y=Y)
        Fecha = self.Date1.get()
        Fecha1 = Fecha[6:10] + "-" + Fecha[3:5] + "-" + Fecha[0:2]
        Fecha = self.Date2.get()
        Fecha2 = Fecha[6:10] + "-" + Fecha[3:5] + "-" + Fecha[0:2]
        try:
            SelectQuery = "SELECT Responsable, SUM(Monto) AS Salario FROM Transactions.dbo.Transactions \
                where Concepto = 'Sueldo' and Fecha between '"                                                              + Fecha1 \
                    + "' and '" + Fecha2 + "' GROUP BY Responsable;"
            Data = pd.read_sql(SelectQuery, conn)
        except:
            df = {
                'Responsable': ['Francisco', 'Guadalupe', 'Diego'],
                'Salario': ['', '', '']
            }
            Data = pd.DataFrame(df)

        tframe_sal = tk.Frame(self.window, bg="blue", highlightcolor="blue")
        tframe_sal.place(x=X + 663, y=Y + 30, height=130, width=318)
        rec, col = Data.shape
        aux = dict()
        data = dict()
        for i in range(rec):
            for j in range(col):
                aux[Data.columns[j]] = Data.values[i, j]
            data['rec' + str(i + 1)] = aux.copy()

        self.model_sal = TableModel()
        self.table_sal = TableCanvas(tframe_sal,
                                     cellbackgr='white',
                                     thefont=(
                                         'Arial',
                                         12,
                                     ),
                                     cellwidth=140,
                                     rowheight=25,
                                     rowheaderwidth=30,
                                     rowselectedcolor='yellow',
                                     editable=False,
                                     model=self.model_sal)
        self.table_sal.createTableFrame()
        self.model_sal = self.table_sal.model
        self.model_sal.importDict(data)
        self.table_sal.show()

        ###### Tabla de Actividades ######
        try:
            SelectQuery = "SELECT #, Fecha, Concepto, Monto, Responsable, Comentario FROM Transactions.dbo.Transactions \
                where Concepto = 'Sueldo' and Responsable = '"                                                               + self.Worker + "' and Fecha between '"+ Fecha1 \
                    + "' and '" + Fecha2 + "';"
            Data = pd.read_sql(SelectQuery, conn)
        except:
            df = {
                '#': [''],
                'Fecha': [''],
                'Concepto': [''],
                'Monto': [''],
                'Responsable': [''],
                'Comentario': ['']
            }
            Data = pd.DataFrame(df)

        tframe_act = tk.Frame(self.window, bg="blue", highlightcolor="blue")
        tframe_act.place(x=X + 80, y=Y + 135, height=350, width=900)
        rec, col = Data.shape
        aux = dict()
        data = dict()
        for i in range(rec):
            for j in range(col):
                aux[Data.columns[j]] = Data.values[i, j]
            data['rec' + str(i + 1)] = aux.copy()

        self.model_act = TableModel()
        self.table_act = TableCanvas(tframe_act,
                                     cellbackgr='white',
                                     thefont=(
                                         'Arial',
                                         12,
                                     ),
                                     cellwidth=140,
                                     rowheight=25,
                                     rowheaderwidth=30,
                                     rowselectedcolor='yellow',
                                     editable=False,
                                     model=self.model_act)
        self.table_act.createTableFrame()
        self.model_act = self.table_act.model
        self.model_act.importDict(data)
        self.table_act.show()

    def update_table(self, event):
        widget = event.widget
        selection = widget.curselection()
        self.Worker = widget.get(selection[0])
        Fecha = self.Date1.get()
        Fecha1 = Fecha[6:10] + "-" + Fecha[3:5] + "-" + Fecha[0:2]
        Fecha = self.Date2.get()
        Fecha2 = Fecha[6:10] + "-" + Fecha[3:5] + "-" + Fecha[0:2]

        try:
            SelectQuery = "SELECT #, Fecha, Concepto, Monto, Responsable, Comentario FROM Transactions.dbo.Transactions \
                where Concepto = 'Sueldo' and Responsable = '"                                                               + self.Worker + "' and Fecha between '"+ Fecha1 \
                    + "' and '" + Fecha2 + "';"
            Data = pd.read_sql(SelectQuery, conn)
        except:
            df = {
                '#': [''],
                'Fecha': [''],
                'Concepto': [''],
                'Monto': [''],
                'Responsable': [''],
                'Comentario': ['']
            }
            Data = pd.DataFrame(df)
        rec, col = Data.shape
        aux = dict()
        data = dict()

        for i in range(rec):
            for j in range(col):
                aux[Data.columns[j]] = Data.values[i, j]
            data['rec' + str(i + 1)] = aux.copy()
        self.model_act.deleteRows(range(0, self.model_act.getRowCount()))
        self.model_act.importDict(data)
        self.table_act.redraw()

        try:
            SelectQuery = "SELECT Responsable, SUM(Monto) AS Salario FROM Transactions.dbo.Transactions \
                where Concepto = 'Sueldo' and Fecha between '"                                                              + Fecha1 \
                    + "' and '" + Fecha2 + "' GROUP BY Responsable;"
            Data = pd.read_sql(SelectQuery, conn)
        except:
            df = {
                'Responsable': ['Francisco', 'Guadalupe', 'Diego'],
                'Salario': ['', '', '']
            }
            Data = pd.DataFrame(df)
        rec, col = Data.shape
        aux = dict()
        data = dict()

        for i in range(rec):
            for j in range(col):
                aux[Data.columns[j]] = Data.values[i, j]
            data['rec' + str(i + 1)] = aux.copy()
        self.model_sal.deleteRows(range(0, self.model_sal.getRowCount()))
        self.model_sal.importDict(data)
        self.table_sal.redraw()
model.importDict(char_dict)  

model2 = table2.model
model2.importDict(sp_char_dict)  


try:
    table.resizeColumn(5, 130) #Position Base
    table.resizeColumn(6, 150) #Is_special_char
    table2.resizeColumn(0, 150) #Special character
    table2.resizeColumn(3, 150) #Position Base
    table2.resizeColumn(4, 150) #Is_special_char
    table2.resizeColumn(5, 550) #loop_string_all
except:
    print("Couldn't resize columns!")
table.redraw()







menubar = tk.Menu(root)

filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=lambda: open_font())
filemenu.add_command(label="Save", command=lambda: save_font("SAVE"))
filemenu.add_command(label="Save as...", command=lambda: save_font("SAVE_AS"))
filemenu.add_command(label="Close", command=lambda: close_font())
filemenu.add_separator()
示例#4
0
class PersonsTab(Frame):
    def __init__(self, notebook):

        #CARACTERÍSTICAS DE LA PESTAÑA
        super().__init__(notebook,
                         bg="#%02x%02x%02x" % (166, 185, 180),
                         highlightthickness=1,
                         highlightbackground="black")
        width = notebook.cget("width") * 3 / 5
        height = notebook.cget("height")

        #TÍTULO DEL PANEL
        Label(self,
              text="LISTA DE PERSONAS REGISTRADAS",
              font=("Verdana", 16, "bold"),
              bg="#%02x%02x%02x" % (166, 185, 180)).place(relx="0.05",
                                                          rely="0.05")

        #BOTÓN PARA CERRAR EL PANEL DE PESTAÑAS
        Button(self,
               text="Cerrar Menú",
               font=("Verdana", 12),
               command=lambda: self.close(notebook)).place(relx="0.85",
                                                           rely="0.05")

        #CREA LA TABLA DE PERSONAS
        self.tableFrame = Frame(self)
        self.model = TableModel()
        self.model.addColumn(colname="DNI")
        self.model.columnwidths["DNI"] = 90
        self.model.addColumn(colname="APELLIDO")
        self.model.columnwidths["APELLIDO"] = 90
        self.model.addColumn(colname="NOMBRES")
        self.model.addColumn(colname="FECHA DE NAC.")
        self.model.columnwidths["FECHA DE NAC."] = 130
        self.model.addColumn(colname="DOMICILIO")
        self.model.columnwidths["DOMICILIO"] = 147
        self.model.addColumn(colname="NACIONALIDAD")
        self.model.columnwidths["NACIONALIDAD"] = 120
        self.model.addColumn(colname="CATEGORÍA")
        self.model.columnwidths["CATEGORÍA"] = 90
        self.model.addColumn(colname="TIPO SANGRE")
        self.model.columnwidths["TIPO SANGRE"] = 110
        self.personsTable = TableCanvas(self.tableFrame,
                                        model=self.model,
                                        width=900,
                                        thefont=("Arial", 10),
                                        read_only=True)
        self.personsTable.show()
        self.tableFrame.place(relx="0.05", rely="0.15")

        self.showPersons()

        #BOTÓN PARA AÑADIR REGISTRO
        Button(self,
               text='AÑADIR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createAddPersonTab()).place(relx=0.1,
                                                                    rely=0.7)

        #BOTÓN PARA MODIFICAR REGISTRO
        Button(self,
               text='MODIFICAR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createModifyPersonTab()).place(
                   relx=0.4, rely=0.7)

        #BOTÓN PARA ELIMINAR REGISTRO
        Button(self,
               text='ELIMINAR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createDeletePersonToplevel()).place(
                   relx=0.7, rely=0.7)

    #FUNCIÓN PARA OBTENER Y CARGAR LAS PERSONAS REGISTRADAS
    def showPersons(self):
        persons = DBManager().getAllPersons()
        self.model.deleteRows()
        dataModel = {}
        for person in persons:
            birthdate = "%02d-%02d-%4d" % (person[3].day, person[3].month,
                                           person[3].year)
            dataModel[person[0]] = {
                'DNI': person[0],
                'APELLIDO': person[1],
                'NOMBRES': person[2],
                'FECHA DE NAC.': birthdate,
                'DOMICILIO': person[4],
                'NACIONALIDAD': person[5],
                'CATEGORÍA': person[6],
                'TIPO SANGRE': person[7]
            }
        self.model.importDict(dataModel)
        self.personsTable.redraw()

    #OBTIENE LA FILA SELECCIONADA
    def getSelectedRow(self):
        return (self.personsTable.get_currentRecord())

    #CERRAR LA PESTAÑA Y ACCIONES COMPLEMENTARIAS
    def close(self, notebook):
        if notebook.addPersonFlag == 0 and notebook.modifyPersonFlag == 0 and notebook.deletePersonFlag == 0:
            notebook.container.personsFlag = 0
            notebook.container.principalFrame.searchBox["state"] = "normal"
            notebook.container.principalFrame.search()
            notebook.destroy()
        else:
            #PARA PODER CERRAR EL PANEL, LAS PESTAÑAS DEBEN ESTAR CERRADAS
            messagebox.showwarning(
                "Advertencia",
                "Para poder cerrar el menú no debe haber ninguna pestaña abierta"
            )
class hostGUI:
    def __init__(self):
        '''
        The host's FTP client instance
        '''
        self.client = HostClient()
        self.fileDownloadClient = HostClient()
        '''
        Boolean for whether we're searching or not. defines the info to load into the table
        '''
        self.searching = False
        '''
        Assemble the GUI
        '''

        self.top = Tk()
        self.top.title("GV-Napster Host")
        self.top.protocol("WM_DELETE_WINDOW", self.onClose)
        #self.top.geometry("700x1200")

        self.fontStyle = tkFont.Font(root=self.top,
                                     family="Helvetica",
                                     size=20)

        self.font = tkFont.Font(family="Helvetica", size=12)

        self.top.option_add("*Font", self.font)

        self.connectionLabelFrame = LabelFrame(self.top, text="Connection")
        self.connectionLabelFrame.pack(fill="both", expand="yes")
        self.searchLabelFrame = LabelFrame(self.top, text="Search")
        self.searchLabelFrame.pack(fill="both", expand="yes")
        self.FTPLabelFrame = LabelFrame(self.top, text="FTP")
        self.FTPLabelFrame.pack(fill="both", expand="yes")

        self.connectionInputs = Frame(self.connectionLabelFrame)

        self.serverHostnameLabel = Label(self.connectionInputs,
                                         text="Server Hostname:")
        self.serverHostnameLabel.grid(row=0, column=0)
        self.serverHostnameText = Entry(self.connectionInputs)
        self.serverHostnameText.grid(row=0, column=1)

        self.usernameLabel = Label(self.connectionInputs, text="Username:"******"Port:")
        self.portLabel.grid(row=0, column=3)
        self.portText = Entry(self.connectionInputs)
        self.portText.grid(row=0, column=4)

        self.hostnameLabel = Label(self.connectionInputs, text="Hostname:")
        self.hostnameLabel.grid(row=1, column=3)
        self.hostnameText = Entry(self.connectionInputs)
        self.hostnameText.grid(row=1, column=4)

        self.speedFrame = Frame(self.connectionLabelFrame)
        self.connSpeedLabel = Label(self.speedFrame, text="Speed:")
        self.connSpeedLabel.pack(side=LEFT)
        self.connSpeedSelection = StringVar(self.top)
        self.speedChoices = {'Ethernet', "TL1", "TL2"}
        self.speedMenu = OptionMenu(self.speedFrame, self.connSpeedSelection,
                                    *self.speedChoices)
        self.speedMenu.pack(side=RIGHT)

        self.connectButton = Button(self.connectionLabelFrame,
                                    text="Connect",
                                    command=self.connect)

        self.searchKeywordFrame = Frame(self.searchLabelFrame)
        self.keywordLabel = Label(self.searchKeywordFrame, text="Keyword:")
        self.keywordLabel.grid(row=0, column=0)
        self.keywordText = Entry(self.searchKeywordFrame)
        self.keywordText.grid(row=0, column=1)
        self.searchButton = Button(self.searchKeywordFrame,
                                   text="Search",
                                   command=self.search)
        self.searchButton.grid(row=0, column=2)
        self.resetSearchButton = Button(self.searchKeywordFrame,
                                        text="Reset",
                                        command=self.resetSearch)
        self.resetSearchButton.grid(row=0, column=3)
        self.updateFileIndexButton = Button(self.searchKeywordFrame,
                                            text="Update File Index",
                                            command=self.updateFileIndex)
        self.updateFileIndexButton.grid(row=0, column=4)

        # working on a table, just a placeholder
        self.searchFrame = Frame(self.searchLabelFrame)
        self.searchTable = TableCanvas(self.searchFrame, width=800)
        self.searchTable.importCSV("files.csv")
        #self.searchTable = Text(self.searchLabelFrame, height=7)

        #removed because server now starts on GUI init
        #self.runServerFrame = Frame(self.FTPLabelFrame)
        #self.runServerButton = Button(self.runServerFrame, text="Start Server", bg="lawn green")
        #self.runServerButton.pack()

        self.getFileFrame = Frame(self.FTPLabelFrame)
        self.fileNameLabel = Label(self.getFileFrame, text="Filename:")
        self.fileNameLabel.grid(row=0, column=0)
        self.fileNameText = Entry(self.getFileFrame)
        self.fileNameText.grid(row=0, column=1)
        self.fileLocationLabel = Label(self.getFileFrame, text="Location:")
        self.fileLocationLabel.grid(row=0, column=2)
        self.fileLocationText = Entry(self.getFileFrame)
        self.fileLocationText.grid(row=0, column=3)
        self.filePortLabel = Label(self.getFileFrame, text="Port:")
        self.filePortLabel.grid(row=0, column=4)
        self.filePortText = Entry(self.getFileFrame)
        self.filePortText.grid(row=0, column=5)
        self.getFileButton = Button(self.getFileFrame,
                                    text="Download File",
                                    command=self.downloadFile)
        self.getFileButton.grid(row=0, column=6)

        self.addFileFrame = Frame(self.FTPLabelFrame)
        self.addFileNameLabel = Label(self.addFileFrame, text="Filename:")
        self.addFileNameLabel.grid(row=0, column=0)
        self.addFileNameText = Entry(self.addFileFrame)
        self.addFileNameText.grid(row=0, column=1)
        self.addFileDescLabel = Label(self.addFileFrame, text="Description:")
        self.addFileDescLabel.grid(row=0, column=2)
        self.addFileDescText = Entry(self.addFileFrame)
        self.addFileDescText.grid(row=0, column=3)
        self.addFileLocationLabel = Label(self.addFileFrame, text="Location:")
        self.addFileLocationLabel.grid(row=0, column=4)
        self.addFileLocationText = Entry(self.addFileFrame)
        self.addFileLocationText.grid(row=0, column=5)
        self.addFilePortLabel = Label(self.addFileFrame, text="Port:")
        self.addFilePortLabel.grid(row=0, column=6)
        self.addFilePortText = Entry(self.addFileFrame)
        self.addFilePortText.grid(row=0, column=7)
        self.speedLabel = Label(self.addFileFrame, text="Speed:")
        self.speedLabel.grid(row=0, column=8)
        self.speedSelection = StringVar(self.top)
        self.speedChoices = {'Ethernet', "TL1", "TL2"}
        self.speedMenu = OptionMenu(self.addFileFrame, self.speedSelection,
                                    *self.speedChoices)
        self.speedMenu.grid(row=0, column=9)
        self.addFileButton = Button(self.addFileFrame, text="Add File")
        self.addFileButton.grid(row=0, column=10)
        '''
        pack all frames in proper order (top to bottom)
        '''
        self.connectionInputs.pack()
        self.speedFrame.pack(side=TOP)
        self.connectButton.pack(side=BOTTOM)
        self.searchFrame.pack()
        self.searchTable.show()
        self.searchKeywordFrame.pack()
        #self.searchTable.pack()
        #self.runServerFrame.pack()
        self.getFileFrame.pack()
        self.addFileFrame.pack()

    def connect(self):
        serverHostname = self.serverHostnameText.get()
        port = self.portText.get()
        username = self.userNameText.get()
        hostname = self.hostnameText.get()
        #speed = self.speedMenu.get()
        self.centralServerPort = port
        self.centralServerURL = serverHostname
        print("Connecting to " + serverHostname + ":" + port + " as " +
              username + " from " + hostname + " at speed <later>...")
        connectionResult = self.client.connect(serverHostname, port, username)
        if (connectionResult == 1):
            messagebox.showerror(title="Server Connection",
                                 message="Connection Refused")
            return
        if (connectionResult == 2):
            messagebox.showerror(title="Server Authentication",
                                 message="Authentication Failed")
        else:
            print("Connected...")
            self.updateFileIndex()

    def downloadFile(self):
        filename = self.fileNameText.get()
        location = self.fileLocationText.get()
        port = self.filePortText.get()
        print("Downloading " + filename + " from " + location)
        self.fileDownloadClient.downloadFile(filename, location, port)

    def addFile(self):
        filename = self.addFileNameText.get()
        description = self.addFileDescText.get()
        location = self.addFileLocationText.get()
        port = self.addFilePortText.get()
        speed = self.speedSelection
        fileParams = [filename, description, location, port, speed]
        fileParams = ",".join(params)
        fullCentralServerURL = self.centralServerURL + ":" + self.centralServerPort
        response = req.request(method='SITE',
                               url=fullCentralServerURL,
                               params=fileParams)

    def search(self):
        print("Searching for keyword in current file index...")
        self.searching = True

        # perform search
        keyword = self.keywordText.get()
        if (keyword == ""):
            return

        self.searchFileIndex(keyword)

        #show results in table
        self.searchTable.importCSV("searchResults.csv")
        self.searchTable.redraw()

    def searchFileIndex(self, keyword):
        self.resetSearchIndex()
        matches = []
        i = 0
        with open('files.csv') as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            for row in readCSV:
                #print(row) # print the array at that row
                #print(row[0]) # print filename of that row
                #print(row[0],row[1],row[2],) # print filename, description, and path of row
                if (keyword in row[0]):
                    matches.append(row)
                    i = i + 1
        print("Number of Files Matching Keyword: " + str(i))

        with open('searchResults.csv', 'w') as searchResults:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(searchResults)
            writer.writerow(row)
            for row in matches:
                print(row)
                #row = row[0] + "," + row[1] + "," + row[2] + "\n"
                writer.writerow(row)

    def resetSearch(self):
        self.searching = False
        self.resetSearchIndex()
        self.searchTable.importCSV("files.csv")
        self.searchTable.redraw()

    def runFTPCommand(self):
        print("Run FTP Command stand-in")

    def updateFileIndex(self):
        print("Updating file index...")
        #print("SEARCHING: " + str(self.searching))
        self.client.fetchFileIndex()
        if (self.searching == False):
            self.searchTable.importCSV("files.csv")
            self.searchTable.redraw()

        print("File index updated...")

    def resetFileIndex(self):
        with open('files.csv', 'w') as files:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(files)

            writer.writerow(row)
            writer.writerow(['   '])

    def resetSearchIndex(self):
        with open('searchResults.csv', 'w') as searchResults:
            row = ['FILENAME', 'DESCRIPTION', 'LOCATION', 'PORT', 'SPEED']
            writer = csv.writer(searchResults)

            writer.writerow(row)
            writer.writerow(['   '])

    def onClose(self):
        print("Resetting file index...")
        self.resetFileIndex()
        print("Resetting search results...")
        self.resetSearchIndex()
        print("Quitting...")
        self.top.destroy()
        sys.exit(0)
示例#6
0
class RRInterface(Frame):
    today = datetime.datetime.now().date()
    pieces = []

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.configure(width=1250, height=500)

        self.frCal = Frame(self)
        self.frCal.place(relx=0, rely=0)
        self.frCal.configure(bd=1, relief=RAISED)
        self.calWidget = tkcalendar.Calendar(self.frCal,
                                             showweeknumbers=False,
                                             locale="ru_RU",
                                             maxdate=self.today)
        self.calWidget.pack()
        self.calWidget.bind('<<CalendarSelected>>', self.getDate)

        self.dayDataFrame = Frame(self)
        self.dayDataFrame.grid_propagate(0)
        self.dayDataFrame.place(relx=0, rely=1, anchor=SW)
        self.dayDataFrame.configure(width=1250,
                                    height=300,
                                    bd=1,
                                    relief=RAISED)

        self.tableModel = TableModel()
        self.table = TableCanvas(self.dayDataFrame,
                                 cellwidth=300,
                                 model=self.tableModel,
                                 rowheight=25)
        self.table.show()

        self.drawFrame = Frame(self)
        self.drawFrame.grid_propagate(0)
        self.drawFrame.place(relx=1, rely=0, anchor=NE)
        self.drawFrame.configure(width=966, height=200, bd=1, relief=RAISED)

        self.createCanvas()

        self.dateList = []
        self.hourUsed = [0 for i in range(24)]

        self.strInfo = StringVar()
        self.labelInfo = Label(self,
                               textvariable=self.strInfo,
                               width=30,
                               height=1,
                               bg='white',
                               bd=1,
                               relief=RAISED,
                               font='Arial 10')
        self.strInfo.set('Test')
        self.labelInfo.place(x=0, y=175)

        self.createFileList()
        self.createTable()
        self.readReportFile(self.today)

    def createCanvas(self):
        self.drawCanvas = Canvas(self.drawFrame, bg='white')
        self.drawCanvas.place(x=0, y=0)
        self.drawCanvas.configure(width=960, height=194)
        for i in range(24):
            self.drawCanvas.create_line((i + 1) * 40,
                                        0, (i + 1) * 40,
                                        180,
                                        fill='black')
            self.drawCanvas.create_text((i + 1) * 40 - 20,
                                        90,
                                        text=str(i),
                                        font="Verdana 14")
        self.drawCanvas.create_line(0, 180, 960, 180, fill='black')

    def getDate(self, event=None):
        date = self.calWidget.selection_get()
        self.readReportFile(date)

    def createFileList(self):
        fileList = glob.glob(reportFolder + "\\*.REP")
        for file in fileList:
            file = file.replace(reportFolder + "\\", "")
            if int(file[1:5]) < 2000:
                continue
            self.dateList.append(
                datetime.date(year=int(file[1:5]),
                              month=monthToInt.get(file[5:8]),
                              day=int(file[8:10])))
        self.dateList.sort()
        if len(self.dateList) > 0:
            self.calWidget.configure(mindate=self.dateList[0])
        else:
            self.calWidget.configure(mindate=datetime.datetime.now())

    def createTable(self):
        data = {
            'def': {
                'Program name': 'test',
                'Start': '00:00:00',
                'End': '23:59:59',
                'Time': '23:59:59',
                'Thickness': 99,
                'Pieces': 999,
                'Produced': 111,
                'Remained': 888,
                'State': 'Ok'
            }
        }
        self.tableModel.importDict(data)
        self.table.resizeColumn(1, 150)
        self.table.resizeColumn(2, 150)
        self.table.resizeColumn(3, 70)
        self.table.resizeColumn(4, 90)
        self.table.resizeColumn(5, 60)
        self.table.resizeColumn(6, 80)
        self.table.resizeColumn(7, 80)

    def readReportFile(self, date):
        # R1970Jan01.REP
        fileName = 'R' + str(date.year) + intToMonth[date.month]
        if date.day < 10:
            fileName = fileName + '0' + str(date.day)
        else:
            fileName = fileName + str(date.day)
        fileName = reportFolder + '\\' + fileName + '.REP'

        self.pieces.clear()
        self.drawCanvas.delete('piece')
        self.tableModel.deleteRows(range(self.tableModel.getRowCount()))
        self.table.redraw()
        if not os.path.exists(fileName):
            self.strInfo.set('File not exist')
            return

        with open(fileName, 'r', encoding="utf-8") as scannedFile:
            fileData = scannedFile.read()
            pieces = fileData.split('\n\n')
            for i in range(len(pieces)):
                lines = pieces[i].split('\n')
                lineDict = {}
                for line in lines:
                    ll = line.replace("\n", "").split('=')
                    if len(ll) < 2:
                        continue
                    lineDict[ll[0]] = ll[1]
                self.pieces.append(
                    PieceData(ID=len(self.pieces),
                              name=lineDict.get('PROGRAM NAME'),
                              start=lineDict.get('START'),
                              end=lineDict.get('END'),
                              time=lineDict.get('MACHINING TIME'),
                              thickness=lineDict.get('WORKPIECE THICKNESS'),
                              pieces=lineDict.get('NUMBER OF PIECES'),
                              produced=lineDict.get('NR OF PIECES PRODUCED'),
                              remained=lineDict.get('NR OF PIECES REMAINING'),
                              state=lineDict.get('STATE'),
                              date=date))
        counter = 0
        while counter < len(self.pieces):
            if self.pieces[counter].programName == '[ERROR]' and self.pieces[
                    counter].id > 0:
                self.pieces.pop(counter)
            else:
                counter += 1
        self.strInfo.set(str(date) + "\t Pieces: " + str(len(self.pieces)))
        self.addDayDataToCanvas()
        self.addDayDataToTable()

    def addDayDataToCanvas(self):
        for i in range(len(self.hourUsed)):
            self.hourUsed[i] = 0

        for piece in self.pieces:
            if piece.programName == '[ERROR]' and piece.id > 0:
                continue
            start = piece.startTime
            end = piece.endTime
            pieceColor = getRandomColor()
            sX = start.hour * 40
            sY = 180 - (start.minute + start.second / 60) * 3
            eX = sX + 40
            eY = 180 - (end.minute + end.second / 60) * 3
            if end.hour != start.hour:
                self.hourUsed[end.hour] += \
                    (end - end.replace(hour=end.hour, minute=0, second=0)).seconds
                currHour = start.hour + 1
                finalHour = end.hour
                if finalHour < currHour:
                    finalHour = 23
                for hH in range(currHour, finalHour):
                    self.drawCanvas.create_rectangle(hH * 40,
                                                     180, (hH + 1) * 40,
                                                     0,
                                                     fill=pieceColor,
                                                     tag="piece")
                    self.hourUsed[hH] += 3600
                tsX = finalHour * 40
                tsY = 180
                teX = tsX + 40
                teY = eY
                eY = 0
                self.drawCanvas.create_rectangle(tsX,
                                                 tsY,
                                                 teX,
                                                 teY,
                                                 fill=pieceColor,
                                                 tag="piece")
                if start.hour < 23:
                    self.hourUsed[start.hour] += (start.replace(
                        hour=start.hour + 1, minute=0, second=0) -
                                                  start).seconds
                else:
                    nextDay = start + datetime.timedelta(seconds=3600)
                    self.hourUsed[start.hour] += (
                        nextDay.replace(hour=0, minute=0, second=0) -
                        start).seconds
            else:
                self.hourUsed[start.hour] += (end - start).seconds

            self.drawCanvas.create_rectangle(sX,
                                             sY,
                                             eX,
                                             eY,
                                             fill=pieceColor,
                                             tag="piece")
        for i in range(24):
            used = toFixed(self.hourUsed[i] / 36, 2)
            tt = self.drawCanvas.create_text(i * 40 + 20,
                                             188,
                                             text=used,
                                             tag="piece")
            if tt > 100000:
                self.drawCanvas.delete('all')
                self.drawCanvas.destroy()
                self.createCanvas()
                self.addDayDataToCanvas()

    def addDayDataToTable(self):
        for piece in self.pieces:
            data = {
                piece.id: {
                    'Program name': piece.programName,
                    'Start': str(piece.startTime),
                    'End': str(piece.endTime),
                    'Time': str(piece.timeTime),
                    'Thickness': piece.thickness,
                    'Pieces': piece.pieces,
                    'Produced': piece.produced,
                    'Remained': piece.remained,
                    'State': piece.state
                }
            }
            self.tableModel.importDict(data)
        self.table.redraw()
示例#7
0
class VehiclesTab(Frame):
    def __init__(self, notebook):

        super().__init__(notebook,
                         bg="#%02x%02x%02x" % (166, 185, 180),
                         highlightthickness=1,
                         highlightbackground="black")

        #TÍTULO DE LA PESTAÑA
        Label(self,
              text="LISTA DE VEHÍCULOS REGISTRADOS",
              font=("Verdana", 16, "bold"),
              bg="#%02x%02x%02x" % (166, 185, 180)).place(relx="0.05",
                                                          rely="0.05")

        #CREA TABLA DE VEHÍCULOS
        self.tableFrame = Frame(self)
        self.model = TableModel()
        self.model.addColumn(colname="DOMINIO")
        self.model.columnwidths["DOMINIO"] = 90
        self.model.addColumn(colname="TITULAR")
        self.model.columnwidths["TITULAR"] = 90
        self.model.addColumn(colname="TIPO")
        self.model.addColumn(colname="MARCA")
        self.model.addColumn(colname="MODELO")
        self.model.columnwidths["MODELO"] = 90
        self.model.addColumn(colname="AÑO")
        self.model.columnwidths["AÑO"] = 75
        self.model.addColumn(colname="VIN")
        self.model.columnwidths["VIN"] = 200
        self.vehiclesTable = TableCanvas(self.tableFrame,
                                         model=self.model,
                                         width=790,
                                         thefont=("Arial", 10),
                                         read_only=True)
        self.vehiclesTable.show()
        self.tableFrame.place(relx="0.10", rely="0.15")
        self.showVehicles()

        #BOTÓN PARA CERRAR LAS PESTAÑAS DE VEHÍCULO
        Button(self,
               text="Cerrar Menú",
               font=("Verdana", 12),
               command=lambda: self.close(notebook)).place(relx="0.85",
                                                           rely="0.05")

        #BOTÓN PARA AÑADIR REGISTRO
        Button(self,
               text='AÑADIR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createAddVehicleTab()).place(relx=0.1,
                                                                     rely=0.7)

        #BOTÓN PARA MODIFICAR REGISTRO
        Button(self,
               text='MODIFICAR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createModifyVehicleTab()).place(
                   relx=0.39, rely=0.7)

        #BOTÓN PARA ELIMINAR REGISTRO
        Button(self,
               text='ELIMINAR REGISTRO',
               width=20,
               font=("Verdana", 14),
               command=lambda: notebook.createDeleteVehicleToplevel()).place(
                   relx=0.68, rely=0.7)

    #FUNCIÓN PARA CARGAR LA TABLE DE VEHÍCULOS
    def showVehicles(self):
        vehicles = DBManager().getAllVehicles()
        self.model.deleteRows()
        dataModel = {}
        for vehicle in vehicles:
            dataModel[vehicle[0]] = {
                'DOMINIO': vehicle[0],
                'TITULAR': vehicle[6],
                'TIPO': vehicle[1],
                'MARCA': vehicle[2],
                'MODELO': vehicle[3],
                'AÑO': str(vehicle[4]),
                'VIN': vehicle[5]
            }
        self.model.importDict(dataModel)
        self.vehiclesTable.redraw()
        #self.vehiclesTable.adjustColumnWidths()

    #DEVUELVE LA FILA SELECCIONADA
    def getSelectedRow(self):
        return (self.vehiclesTable.get_currentRecord())

    #CIERRA EL PANEL ACTUAL Y REALIZA LOS CAMBIOS CORRESPONDIENTES.
    #PARA CERRAR EL PANEL, LOS PANELES DE CREACIÓN, MODIFICACIÓN Y ELIMINACIÓN DEBEN ESTAR CERRADOS
    def close(self, notebook):
        if notebook.addVehicleFlag == 0 and notebook.modifyVehicleFlag == 0 and notebook.deleteVehicleFlag == 0:
            notebook.container.vehiclesFlag = 0
            notebook.container.principalFrame.searchBox["state"] = "normal"
            notebook.container.principalFrame.search()
            notebook.destroy()
        else:
            messagebox.showwarning(
                "Advertencia",
                "Para poder cerrar el menú no debe haber ninguna pestaña abierta"
            )
class ResultSearchTab(Frame):
    def __init__(self, frame):

        #CARACTERÍSTICAS DEL PANEL
        width = frame.cget("width") * 3 / 5
        height = frame.cget("height")
        bgcolor1 = "#%02x%02x%02x" % (157, 168, 244)
        super().__init__(frame,
                         bg=bgcolor1,
                         highlightthickness=1,
                         highlightbackground="black")

        #TITULO DE VENTANA
        Label(self,
              text="DATOS DEL VEHÍCULO",
              font=("Verdana", 14, "bold"),
              bg=bgcolor1).place(relx=0.35, rely=0.04)

        #PANEL DE DATOS DEL VEHÍCULO
        dataVehicle = Frame(self, bg=bgcolor1, width=width, height=100)
        dataVehicle.place(relx=0.02, rely=0.1)
        bgcolor2 = "#%02x%02x%02x" % (198, 204, 249)

        Label(dataVehicle,
              text="Dominio",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=1, column=1)
        Label(dataVehicle,
              text="Tipo",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=1, column=3)
        Label(dataVehicle,
              text="N° de Motor",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=1, column=5)
        Label(dataVehicle,
              text="Marca",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=2, column=1)
        Label(dataVehicle,
              text="Modelo",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=2, column=3)
        Label(dataVehicle,
              text="Año",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=2, column=5)
        Label(dataVehicle,
              text="Titular",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=3, column=1)
        Label(dataVehicle,
              text="DNI",
              width=15,
              bg=bgcolor1,
              relief="groove",
              borderwidth=4,
              font=("Verdana", 11, "italic")).grid(row=3, column=5)

        #DOMINIO
        self.domainLabel = Label(dataVehicle,
                                 font=("Verdana", 12, "italic"),
                                 width=15,
                                 bg=bgcolor2)
        self.domainLabel.grid(row=1, column=2)

        #TIPO DE VEHÍCULO
        self.kindLabel = Label(dataVehicle,
                               font=("Verdana", 12, "italic"),
                               width=15,
                               bg=bgcolor2)
        self.kindLabel.grid(row=1, column=4)

        #NÚMERO DE MOTOR
        self.engineLabel = Label(dataVehicle,
                                 font=("Verdana", 12, "italic"),
                                 width=20,
                                 bg=bgcolor2)
        self.engineLabel.grid(row=1, column=6)

        #MARCA
        self.brandLabel = Label(dataVehicle,
                                font=("Verdana", 12, "italic"),
                                width=15,
                                bg=bgcolor2)
        self.brandLabel.grid(row=2, column=2)

        #MODELO
        self.modelLabel = Label(dataVehicle,
                                font=("Verdana", 12, "italic"),
                                width=15,
                                bg=bgcolor2)
        self.modelLabel.grid(row=2, column=4)

        #AÑO
        self.yearLabel = Label(dataVehicle,
                               font=("Verdana", 12, "italic"),
                               width=20,
                               bg=bgcolor2)
        self.yearLabel.grid(row=2, column=6)

        #TITULAR
        self.titularLabel = Label(dataVehicle,
                                  font=("Verdana", 12, "italic"),
                                  anchor="w",
                                  width=45,
                                  bg=bgcolor2)
        self.titularLabel.grid(row=3, column=2, columnspan=3)

        #DNI DEL TITULAR
        self.dniLabel = Label(dataVehicle,
                              font=("Verdana", 12, "italic"),
                              width=20,
                              bg=bgcolor2)
        self.dniLabel.grid(row=3, column=6)

        #CREA TABLA DE INFRACCIONES
        self.tableFrame = Frame(self)
        self.model = TableModel()
        self.model.addColumn(colname="ID")
        self.model.columnwidths["ID"] = 80
        self.model.addColumn(colname="DNI RESPONSABLE")
        self.model.columnwidths["DNI RESPONSABLE"] = 90
        self.model.addColumn(colname="CAUSA")
        self.model.addColumn(colname="AGENTE")
        self.model.addColumn(colname="FECHA")
        self.model.addColumn(colname="LUGAR")
        self.model.addColumn(colname="MONTO")
        self.model.columnwidths["MONTO"] = 70
        self.model.addColumn(colname="PAGADO")
        self.model.columnwidths["PAGADO"] = 70
        self.infractionsTable = TableCanvas(self.tableFrame,
                                            model=self.model,
                                            width=938,
                                            thefont=("Arial", 10),
                                            read_only=True)
        self.infractionsTable.show()
        self.tableFrame.place(x="20", rely="0.35")

        #CREA MENSAJE DE ESTADO DE CUENTA
        self.message = StringVar()
        self.debtLabel = Label(self,
                               textvariable=self.message,
                               font=("Verdana", 12))
        self.debtLabel.place(x="30", rely="0.30")

    #FUNCIÓN QUE DEVUELVE LA FILA SELECCIONADA
    def getSelectedRow(self):
        return (self.infractionsTable.get_currentRecord())

    #FUNCIÓN QUE CARGA EL PANEL Y LA TABLA DE INFRACCIONES CON LOS DATOS CORRESPONDIENTES
    def showData(self, data):
        self.model.deleteRows()
        dataModel = {}

        if data != None:
            self.domainLabel.configure(text=data[0])
            self.kindLabel.configure(text=data[1])
            self.brandLabel.configure(text=data[2])
            self.modelLabel.configure(text=data[3])
            self.yearLabel.configure(text=data[4])
            self.engineLabel.configure(text=data[5])
            self.titularLabel.configure(text=data[7] + ", " + data[8])
            self.dniLabel.configure(text=data[6])

            infractions = DBManager().getInfractions(data[0])
            self.debt = 0.00
            for infraction in infractions:
                isPay = 'NO'
                if (infraction[8] == 1):
                    isPay = 'SI'
                dateandhour = "%02d-%02d-%4d %02d:%02d" % (
                    infraction[5].day, infraction[5].month, infraction[5].year,
                    infraction[5].hour, infraction[5].minute)
                dateandhourpaid = "-"
                if (infraction[9] != None):
                    dateandhourpaid = "%02d-%02d-%4d %02d:%02d" % (
                        infraction[9].day, infraction[9].month,
                        infraction[9].year, infraction[9].hour,
                        infraction[9].minute)
                dataModel[infraction[0]] = {
                    'ID': "%07d" % (infraction[0]),
                    'DNI RESPONSABLE': str(infraction[1]),
                    'CAUSA': str(infraction[3]),
                    'AGENTE': str(infraction[4]),
                    'FECHA': dateandhour,
                    'LUGAR': str(infraction[6]),
                    'MONTO': "%.2f" % (infraction[7]),
                    'PAGADO': isPay,
                    'FECHA PAGO': dateandhourpaid
                }
                if (infraction[8] == 0):
                    self.debt = self.debt + float(infraction[7])
            if (self.debt > 0):
                self.message.set("Presenta una deuda de $ " + str(self.debt))
            else:
                self.message.set("No presenta deudas.")
        #SI LA BÚSQUEDA NO ARROJA RESULTADOS, LOS CAMPOS SE MUESTRAN EN BLANCO
        else:
            self.domainLabel.configure(text="")
            self.kindLabel.configure(text="")
            self.brandLabel.configure(text="")
            self.modelLabel.configure(text="")
            self.yearLabel.configure(text="")
            self.engineLabel.configure(text="")
            self.titularLabel.configure(text="")
            self.dniLabel.configure(text="")
            self.message.set("")

        #ACTUALIZA EL CONTENIDO DE LA TABLA
        self.model.importDict(dataModel)
        self.infractionsTable.redraw()
        self.infractionsTable.autoResizeColumns()
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        font9 = "-family {Segoe UI} -size 14 -weight bold"
        font91 = "-family {Segoe UI} -size 8 -weight bold"

        top.geometry("600x450+406+135")
        top.title("New Toplevel")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.0, rely=-0.022, height=831, width=1380)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="#000000")
        self.Label1.configure(background="#0d0819")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(font=font9)
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        photo_location = os.path.join(prog_location,"art.png")
        self._img0 = tk.PhotoImage(file=photo_location)
        self.Label1.configure(image=self._img0)
        #self.Label1.configure(text='''Label''')

        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.35, rely=0.689, height=71, width=304)
        self.Label2.configure(activebackground="#f9f9f9")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(font=font9)
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#d9d9d9")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text=z)


##
       # the_text_widget = tk.Text(top,height=4,width=50)
        #data=""
##        with open("sub.csv", "r") as f:
##                  data1 = f.read()
##                  data=data + data1[8:]
##                 # the_text_widget.insert("1.0", data)

       
        
##        with open("sub.csv") as inf:
##            rowr=csv.reader(inf,delimiter=',')
##            a=tabulate(rowr)

           
        self.tframe = tk.Frame(top)
       
        self.tframe.pack()
        
        
        table = TableCanvas(self.tframe,cellwidth=5000, width="1000",	
                 
               editable=False
              )
       
       
        
       

        table.show()
    
       
        
        
        table.redraw()
        
        table.importCSV("sub.csv")