jugujcgm / GUI2

0 stars 0 forks source link

Tablas de Excel deben ser integradas en la aplicacion "Analyser tool" #2

Open jugujcgm opened 1 year ago

jugujcgm commented 1 year ago

Hasta ahora solo un bosquejo ha sido creado

AlonsoFM12 commented 1 year ago

Primo, no supe en que parte agregarlo en file _and_uses_headler, char_handler o page run analysis.

Esta clase permite al usuario seleccionar la cantidad de headers para la tabla y la genera dentro de la GUI, el inconveniente es que se genera el archivo y posteriormente se tiene que seleccionar el archivo.

`import tkinter as tk from tkinter import ttk from tkinter import filedialog import openpyxl

class TableGenerator: def init(self): self.tables_window = tk.Tk() self.tables_window.geometry("500x600") self.combobox_countx = 0 self.comboboxesx = [] self.labels = [] self.X = [] self.option = ["Sequence", "Serial Number", "Date", "Time", "UID", "Alarm", "Power", "Error", "Event", "Fcheck"]

    # create a label with the heading
    header = tk.Label(self.tables_window, text="Select the table headers",
                      bg="yellow",
                      font=("consolas", 15, "bold"))
    header.place(x=10, y=10, width=300, height=40)

    # create a new label, an entry and a button
    num_comboboxes_label = tk.Label(self.tables_window, text="Number of columns:",
                                    font=("consolas", 12))
    num_comboboxes_label.place(x=30, y=60, width=150, height=20)

    self.num_comboboxes_entry = tk.Entry(self.tables_window)
    self.num_comboboxes_entry.place(x=190, y=60, width=50, height=20)

    num_comboboxes_button = tk.Button(self.tables_window,
                                      text="Confirm",
                                      font=("consolas", 11),
                                      command=self.create_comboboxes)
    num_comboboxes_button.place(x=250, y=60, width=100, height=20)

    # create a new label with outline which will contain the comboboxes that the user wants to generate.
    self.selection_box = tk.LabelFrame(self.tables_window, text="Selection box", font=("consolas", 10, ""))
    self.selection_box.place(x=10, y=90)

    create_graphics_button = tk.Button(self.tables_window,
                                       text="Create Table",
                                       font=("consolas", 11),
                                       command=self.create_table)
    create_graphics_button.place(x=400, y=60, width=150, height=20)

    open_file_button = tk.Button(self.tables_window, text="Open Table", font=("consolas", 11), command=self.open_table)
    open_file_button.place(x=400, y=100, width=150, height=30)

def create_comboboxes(self):
    num_comboboxes = int(self.num_comboboxes_entry.get())

    # delete comboboxes and labels in case of an error
    for widget in self.comboboxesx + self.labels:
        widget.destroy()
    self.comboboxesx.clear()
    self.labels.clear()

    # for loop to create comboboxes and header tags
    for i in range(num_comboboxes):

        label = tk.Label(self.selection_box, text=f"Graphic {i + 1}          ")
        label.grid(column=0, row=i * 2)
        self.labels.append(label)

        label = tk.Label(self.selection_box, text=f"X{i + 1}-axis")
        label.grid(column=1, row=i * 2)
        self.labels.append(label)

        combobox = ttk.Combobox(self.selection_box, width=15, values=self.option, state="readonly")
        combobox.grid(column=2, row=i * 2)
        self.comboboxesx.append(combobox)

    self.combobox_countx = num_comboboxes
    self.X = []

def create_table(self):
    wb = openpyxl.Workbook()
    ws = wb.active

# Creates the table header
    for i in range(self.combobox_countx):
        self.X.append(self.comboboxesx[i].get())
        ws.cell(row=1, column=i+1, value=self.X[i])

# Save the file as an Excel file
    wb.save("my_table.xlsx")

def open_table(self):
    file_path = filedialog.askopenfilename(defaultextension=".xlsx",
                                           filetypes=[("Excel Workbook", "*.xlsx"),
                                                      ("Excel 97-2003 Workbook", "*.xls")])
    if file_path:
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active

        # Get the number of rows and columns
        num_cols = ws.max_column
        num_rows = ws.max_row

        # Create a table inside the main window
        table_frame = tk.Frame(self.tables_window)
        table_frame.place(x=10, y=600, width=1500, height=380)

        table_scrollbar = ttk.Scrollbar(table_frame, orient="horizontal")
        table_scrollbar.pack(side="bottom", fill="x")

        table = ttk.Treeview(table_frame, columns=tuple(range(num_cols)), show="headings", xscrollcommand=table_scrollbar.set)
        table.pack(side="left", fill="both")

        table_scrollbar.config(command=table.xview)

        # Configure column headers
        for i in range(num_cols):
            col_name = ws.cell(row=1, column=i+1).value
            table.heading(i, text=col_name)

        # Add data to the table
        for i in range(2, num_rows+1):
            row_data = []
            for j in range(num_cols):
                cell_value = ws.cell(row=i, column=j+1).value
                row_data.append(cell_value)
            table.insert("", "end", values=row_data)

`

jugujcgm commented 1 year ago

Hola. Lo mejor es separar el código en dos partes. La primera parte se va a encargar de recabar toda la información requerida. Por ejemplo: "Select the table headers", "Number of columns" etc. La segunda parte se va a encargar de crear el archivo (tipo excel), rellenar la hoja de excel con la información que el usuario necesita y después desplegar el resultado. Yo creo que lo mejor es informarle al usuario que la tabla de excel fue creada en la carpeta "xxx bla bla bla" y después preguntarle al usuario si quiere cerrar la aplicación y abrir la tabla de excel o si simplemente quiere cerrar la aplicación. La primera parte se debe poner en _page_defineanalyse.py. De hecho ahí ya existe el _radiobutton16 y este hace el callback a la función _DefAnaPAga.do_whenexcel La segunda parte se debe poner en _page_runanalysis.py Cuando ya tengas la primera parte me llamas por teléfono y juntos vemos en dónde tiene que ir la segunda parte. Esto no te lo digo por mensaje porque es bastante más complicado.

AlonsoFM12 commented 1 year ago

Primo, ya puse la primera parte en _page_defineanalyse.py.

También empecé a trabajar con las tablas y ya avancé en la parte de la búsqueda sin la necesidad de usar [tab], pero creo que habría que cambiar algunas cosas, por eso no las he implementado en el código que me pasaste.

Anexo la clase principal y las 3 funciones que agregué, en la funcion _createtable puse 2 códigos, el primero está comentado, que es para crear el archivo de Excel y posteriormente mandarlo a llamar o la segunda opción es guardar los headers en una lista y llamarla más adelante, esto por el código en el que ya trabajo con las tablas pero dentro de la GUI.

No se si puedas marcarme el lunes a la misma hora que la vez pasada

` import tkinter as tk from tkinter import ttk from tkinter import filedialog import openpyxl

class DefAnaPage(tk.Frame): def init(self, parent, controller): tk.Frame.init(self, parent) self.controller = controller

create a hint label

    label_hint3 = tk.Label(self, text = "Select the device")
    label_hint3.grid(row=0, column=0, sticky='n', pady=30, padx=20, columnspan=2)
    # create the radio buttons of device type
    self.radio_button3 = tk.Radiobutton(self, text = "MMS2", variable = self.controller.device, \
        value = 1, command = lambda: DefAnaPage.do_when_device_selected(self, 1))
    self.radio_button3.grid(row=1, column=0, padx=20)
    self.radio_button4 = tk.Radiobutton(self, text = "MVS", variable = self.controller.device, \
        value = 2, command = lambda: DefAnaPage.do_when_device_selected(self, 2))
    self.radio_button4.grid(row=1, column=1, pady=5, padx=5)
    self.radio_button5 = tk.Radiobutton(self, text = "MeduT", variable = self.controller.device, \
        value = 3, command = lambda: DefAnaPage.do_when_device_selected(self, 3))
    self.radio_button5.grid(row=1, column=2, pady=5, padx=5)
    self.radio_button6 = tk.Radiobutton(self, text = "MCS2", variable = self.controller.device, \
        value = 4, command = lambda: DefAnaPage.do_when_device_selected(self, 4))
    self.radio_button6.grid(row=1, column=3, pady=5, padx=5)
    # create a button to change the page
    validation = tk.Button(self, text='CONTINUE', command= lambda: DefAnaPage.change_page(self))
    validation.grid(row=0, column=2, pady=5, padx=5)

########## Nothing was changed in the code that was already there, only 3 functions were added at the end #######

def do_when_excel(self):
    header = tk.Label(self, text="Select the table headers", font=("consolas", 15, "bold"))
    header.grid(row=9, column=0, pady=5, padx=5)

    # create a new label, an entry and a button
    num_comboboxes_label = tk.Label(self, text="Number of columns:", font=("consolas", 12))
    num_comboboxes_label.grid(row=10, column=0, pady=5, padx=5)

    self.num_comboboxes_entry = tk.Entry(self)
    self.num_comboboxes_entry.grid(row=10, column=1, pady=5, padx=5)

    num_comboboxes_button = tk.Button(self, text="Confirm", font=("consolas", 11), command=lambda: DefAnaPage.create_comboboxes(self))
    num_comboboxes_button.grid(row=10, column=2, pady=5, padx=5)

    # create a new label with outline which will contain the comboboxes that the user wants to generate.
    self.selection_box = tk.LabelFrame(self, text="Selection box", font=("consolas", 10, ""))
    self.selection_box.grid(row=11, column=0, pady=5, padx=5)

    create_graphics_button = tk.Button(self, text="Create Table", font=("consolas", 11), command=lambda: DefAnaPage.create_table(self))
    create_graphics_button.grid(row=11, column=2, pady=5, padx=5)

'''This code is a function called create_comboboxes that creates a specified number
of comboboxes in a graphical user interface (GUI) using the Python Tkinter library.

Here is a description of the key parts of the function:

self.comboboxesx and self.labels are two empty lists used to store references to the 
Combobox and Label objects that are created in the function.

self.option is a list of strings that is used as the values available in the comboboxes
that are created. Each string is an option that is displayed in the combobox drop-down menu.

num_comboboxes is an integer that is specified in an entry in the GUI. This variable 
determines how many comboboxes are created.

The for block starting at for i in range(num_comboboxes): is where the Combobox and Label 
objects are created. For each iteration of the loop, a label pair and a combobox are 
created, and added to the self.labels and self.comboboxesx lists, respectively. The values 
of i are used to label the created objects with sequential numbers.

Finally, self.combobox_countx is updated with the number of comboboxes created, and self.X
  is initialized as an empty list.

In summary, this function creates a specific number of comboboxes and labels and adds them
  to a GUI. The user can select an option in each combobox, which can be used to perform 
  additional actions in the application.'''

def create_comboboxes(self):
    self.comboboxesx = []
    self.labels = []  
    self.option = ["Sequence", "Serial Number", "Date", "Time", "UID", "Alarm", "Power", "Error", "Event", "Fcheck"]
    num_comboboxes = int(self.num_comboboxes_entry.get())

    # delete comboboxes and labels in case of an error
    for widget in self.comboboxesx + self.labels:
        widget.destroy()
    self.comboboxesx.clear()
    self.labels.clear()

    # for loop to create comboboxes and header tags
    for i in range(num_comboboxes):

        label = tk.Label(self.selection_box, text=f"Graphic {i + 1}          ")
        label.grid(column=0, row=i * 2)
        self.labels.append(label)

        label = tk.Label(self.selection_box, text=f"X{i + 1}-axis")
        label.grid(column=1, row=i * 2)
        self.labels.append(label)

        combobox = ttk.Combobox(self.selection_box, width=15, values=self.option, state="readonly")
        combobox.grid(column=2, row=i * 2)
        self.comboboxesx.append(combobox)

    self.combobox_countx = num_comboboxes

def create_table(self):
    ###This part will be used in case you need to create the list and work with it.
    ####See the possibility of eliminating the creation of the list and working directly with pandas

    '''
    self.X = [] 
    wb = openpyxl.Workbook()
    ws = wb.active

    # Creates the table header
    for i in range(self.combobox_countx):
        self.X.append(self.comboboxesx[i].get())
        ws.cell(row=1, column=i+1, value=self.X[i])

    # Save the file as an Excel file
    wb.save("my_table.xlsx")'''

    #this part is to save the headers in a list, in case they are used at some point.
    headers_comboboxes = []
    for header in self.comboboxesx:
        headers = header.get()
        headers_comboboxes.append(headers)
    print(headers_comboboxes)`
jugujcgm commented 1 year ago

Te hablo hoy

AlonsoFM12 commented 1 year ago

primo, no se si se pueda mañana, ahorita ya voy de salida para la escuela ,por que tengo que entregar los papeles para la toma de protesta.