Esempio n. 1
0
class create_csv():
    def __init__(self, root):
        self.f = Frame(root, height=500, width=500)
        self.f.pack()

        self.message_label = Label(self.f,
                                   text='Display the Empsal CSV:',
                                   font=('Roman', 24, 'bold'),
                                   fg='navy blue')
        self.confirm_button = Button(self.f,
                                     text='Display',
                                     font=('Arial', 14),
                                     bg='light green',
                                     fg='White',
                                     command=self.conv_to_csv,
                                     activeforeground='green')
        self.exit_button = Button(self.f,
                                  text='Exit',
                                  font=('Arial', 14),
                                  bg='pink',
                                  fg='White',
                                  command=root.destroy,
                                  activeforeground='red')

        self.message_label.grid(row=1, column=1)
        self.confirm_button.grid(row=3, column=0)
        self.exit_button.grid(row=3, column=2)

    def conv_to_csv(self):
        self.f = Frame(root, height=300, width=300)
        self.f.pack(fill=BOTH, expand=1)

        self.table = TableCanvas(self.f, read_only=True)
        self.table.importCSV('empsal.csv')
        self.table.show()
Esempio n. 2
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()
Esempio n. 3
0
def show_transaction_table(frame, frame1):
    model = TableModel()
    transactionItems = transactions_database.getData()

    data = {}
    data1 = {}

    totalSale = 0.0

    for i in range(len(transactionItems)):
        totalSale += float(transactionItems[i][1])

    for i in range(len(transactionItems)):
        data['row' + str(i + 1)] = {
            'Name': transactionItems[i][0],
            'S.Price': transactionItems[i][1],
            'Date': transactionItems[i][2]
        }

        data1['row1'] = {'Total ($)': totalSale}

        table1 = TableCanvas(frame1, data=data1, takefocus=0)
        table = TableCanvas(frame, data=data, takefocus=0)

        table.show()
        table1.show()
def CreateTable(Main, Data):
    
    tframe = tk.Frame(Main,
                      bg ="blue",
                      highlightcolor = "blue") 
    tframe.place(x = 50, y =275,
                 height = 275, width =1100)
    
    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()
    
    model = TableModel()    
    table = TableCanvas(tframe, cellbackgr='white', 
    			thefont=('Arial',12, ), cellwidth = 100 ,
                rowheight=25, rowheaderwidth=30,
    			rowselectedcolor='yellow', editable=False,
                model = model)
    table.createTableFrame()
    model = table.model
    model.importDict(data)

    table.show()
    return table, model
Esempio n. 5
0
class create_csv:

     def __init__(self, root):
          self.f = Frame(root, height=350, width=500)
          self.f.pack()    # Place the frame on root window

          # Creating label widgets
          self.message_label = Label(self.f,text='Display the Empsal CSV in TkinterTable',font=('Arial', 14))

          # Buttons
          self.confirm_button = Button(self.f,text='Display', font=('Arial', 14), bg='Orange',
                                 fg='Black', command=self.conv_to_csv)
          self.exit_button = Button(self.f,text='Exit', font=('Arial', 14), bg='Yellow',
                                 fg='Black', command=root.destroy)

          # Placing the widgets using grid manager
          self.message_label.grid(row=1, column=0)
          self.confirm_button.grid(row=2,column=0)
          self.exit_button.grid(row=2,column=2)

     def conv_to_csv(self):

         try:

             # Now display the CSV in 'tkintertable' widget
             self.f = Frame(root, height=200, width=300)
             self.f.pack(fill=BOTH,expand=1)
             self.table = TableCanvas(self.f, read_only=True)
             self.table.importCSV('empsal.csv')
             self.table.show()

         except FileNotFoundError as e:
             msg.showerror('Error in opening file', e.msg)
Esempio n. 6
0
    def display_leaderboard(self):
        self.cursor.execute(
            'SELECT player.username, MAX(data.kills) AS kills, data.date FROM data INNER JOIN player ON data.playerID = player.playerID GROUP BY username limit 0, 10 '
        )
        result = self.cursor.fetchall()
        data = Convert(result)

        kills_dict = dict()
        for key in data:
            data_value = list(data[key].values())
            kills_dict[key] = data_value[1]

        kills_dict = mergeSortDict(kills_dict, ascending=False)

        final_dict = dict()

        for key in kills_dict:
            final_dict[key] = data[key]

        tframe = Frame(self.my_w)
        tframe.pack()
        model = TableModel()
        table = TableCanvas(tframe,
                            model=model,
                            data=final_dict,
                            editable=False,
                            width=800,
                            height=300)
        table.show()
        self.my_w.mainloop()
Esempio n. 7
0
        def __init__(self,tktk = None,
                        br_image = None,
                        pathico = None,
                        br_image_path = None):

                Frame.__init__(self, tktk)
                self.tktk = tktk

                self.br_image_path  = br_image_path

                self.br_image = br_image

                self.pathico = pathico

                self.filewin = Toplevel(self.tktk)

                gui (tktk=self.filewin,
                        pathico=self.pathico,
                        width=1280,
                        height=1024,
                        widthx=300,
                        widthy=0,
                        resizable=[True,True]).setcfbs()
                        
                # set data
                data = createData()
                menu (tktk=self.filewin).createmenu()

                #create label 
                self.framelb = Frame(self.filewin,bg = "slate gray")
                self.framelb.pack(side = TOP)

                #creare frame for infomation
                self.frameinfor = Frame(self.filewin,bg = "slate gray")
                self.frameinfor.pack(side = TOP)


                #create title 
                self.framett = Frame(self.filewin,bg = "slate gray")
                self.framett.pack(side = TOP)

                # creare frame for table  
                self.tframe = Frame(self.filewin)
                self.tframe.pack(fill = X,side = TOP)

                model = TableModel()
                table = TableCanvas(self.tframe, model=model,data=data,height=650)
                table.show()

               #update quotation
                self.frameupdate = Frame(self.filewin,bg = "slate gray")
                self.frameupdate.pack(side = TOP)
                
                # import and export excel 
                self.frameimeex = Frame(self.filewin,bg = "slate gray")
                self.frameimeex.pack(side = TOP)


                self.createguiin()
Esempio n. 8
0
class TestApp():
    def __init__(self,root):
        self.f=Frame(root,height=200,width=100)
        self.f.pack(fill=BOTH,expand=1)
        self.table=TableCanvas(self.f,read_only=True)
        self.table.importCSV('/media/amit/Work/GitHub/Machine Learning with Python/DataSets/empsal.csv')
        print(self.table.model.columnNames)
        self.table.show()
Esempio n. 9
0
def table_gui(data):
    tframe = Frame(master)
    tframe.pack()
    table = TableCanvas(tframe)
    table.show()


#if __name__ == '__main__': main()
Esempio n. 10
0
class TestApp():
    def __init__(self, root):
        self.f = Frame(root, height=200, width=300) 
        self.f.pack(fill=BOTH,expand=1)
        
        self.table = TableCanvas(self.f, read_only=True)
        self.table.importCSV('exp_sal.csv')
        print (self.table.model.columnNames)
        self.table.show()
Esempio n. 11
0
def ClearTable():

    DataTracking.Question = []
    DataTracking.Answers = []
    DataTracking.Correct = []

    Data = {}
    model = TableModel()
    table = TableCanvas(tframe, data=Data)
    table.show()
Esempio n. 12
0
def LoadWebPage():

    HtmlFile = filedialog.askopenfilename()
    File = open(HtmlFile, encoding='utf-8')
    soup = BeautifulSoup(File.read(), features="html.parser")
    Data = GetQuestions.GetAnswers(soup)

    model = TableModel()
    table = TableCanvas(tframe, data=Data)
    table.thefont = ('Arial', 10)
    table.show()
Esempio n. 13
0
class View:
    def __init__(self, root, model, controller):
        self.model = model
        self.root = root
        self.controller = controller
        self.popup = Popup(model)

        # Table setup
        self.frame_table = tk.Frame(root)
        self.table = TableCanvas(self.frame_table)
        self.table.show()

        self.frame_table.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # Buttons setup
        self.frame_buttons = tk.Frame(root)
        # Event handlers
        self.btn_open = tk.Button(self.frame_buttons, text="Open", command=self.controller.openFile)
        self.btn_search = tk.Button(self.frame_buttons, text="Search", command=self.controller.findValue)
        self.btn_statistics = tk.Button(self.frame_buttons, text="Statistics", command=self.controller.getMinMax)
        self.btn_plot = tk.Button(self.frame_buttons, text="Show plot", command=self.controller.openPlot)

        # Grid setup
        self.btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
        self.btn_search.grid(row=1, column=0, sticky="ew", padx=5, pady=5)
        self.btn_statistics.grid(row=2, column=0, sticky="ew", padx=5, pady=5)
        self.btn_plot.grid(row=3, column=0, sticky="ew", padx=5, pady=5)

        self.frame_buttons.pack(side=tk.LEFT, fill=tk.BOTH)

        #Window setup
        self.root.rowconfigure(0, minsize=800, weight=1)
        self.root.columnconfigure(1, minsize=800, weight=1)
        self.root.title("Log viewer")

    #Methods
    def showData(self):
        """Show data in te table"""
        self.table = TableCanvas(self.frame_table, data=self.model.dictdata, read_only=True)
        self.table.adjustColumnWidths()
        self.table.show()

    def setTitle(self):
        """Set root title with filepath"""
        self.root.title(f"Log Viewer - {self.controller.filepath}")

    def showSearchResult(self, row, col):
        """Show cell with search result in the table"""
        self.table.delete('searchrect')
        self.table.drawRect(row, col, color='red', tag='searchrect', delete=0)
        self.table.lift('searchrect')
        self.table.lift('celltext'+str(col)+'_'+str(row))
 def __init__(self, parent=None):
     self.parent = parent
     Frame.__init__(self)
     self.main = self.master
     self.main.geometry('800x500+200+100')
     self.main.title(weather)
     f = Frame(self.main)
     f.pack(fill=BOTH, expand=1)
     table = TableCanvas(f, data=data2)
     # table.redrawTable()
     # table.model.data[0]['col1'] = 'XX'
     # print(table.model.columnNames)
     table.show()
     return
Esempio n. 15
0
class Timetable(Frame):

    def __init__(self, parent=None):
        self.parent = parent
        Frame.__init__(self)
        self.main = self.master
        self.main.geometry('800x500+0+0')
        self.main.title('Sequences of Shifts')
        f = Frame(self.main)
        f.pack(fill=BOTH,expand=1)
        self.table = TableCanvas(f, data=data, cellwidth=150, cellbackgr='#E3F6CE',read_only=True,rowselectedcolor='yellow',rowheaderwidth=100,showkeynamesinheader=True)
        self.table.show()
        return
    def redraw(self):
      self.table.redrawTable()
Esempio n. 16
0
 def __init__(self, parent=None):
     self.parent = parent
     Frame.__init__(self)
     self.main = self.master
     self.main.geometry('800x500+200+100')
     self.main.title('Test')
     f = Frame(self.main)
     f.pack(fill=BOTH, expand=1)
     table = TableCanvas(f, data=data)
     # table.importCSV('test.csv')
     print(table.model.columnNames)
     # table.model.data[1]['a'] = 'XX'
     # table.model.setValueAt('YY',0,2)
     table.show()
     return
Esempio n. 17
0
    def postupdate(self):
        items = item_database.getData()
        print(len(items))
        data = {}

        for i in range(len(items)):
            data['row' + str(i + 1)] = {
                'Name': items[i][0],
                'Barcode': items[i][1],
                'P.Price': items[i][2],
                'S.Price': items[i][3],
                'Quantity': items[i][4]
            }

        table = TableCanvas(self.itemsListFrame, data=data)
        table.show()
Esempio n. 18
0
def create_gui():
    root.title("XCOM Soldier Viewer")
    width = 1600
    height = 900
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width / 2) - (width / 2)
    y = (screen_height / 2) - (height / 2)
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))
    root.resizable(0, 0)

    tframe = Frame(root)
    tframe.pack(fill="both", expand=True)
    table = TableCanvas(tframe, editable=False)
    table.importCSV('soldiers.csv')
    table.show()
    table.update()
Esempio n. 19
0
 def display_personal_statistics(self, LOGGEDIN_PLAYERID):
     self.cursor.execute(
         'SELECT player.username, data.kills, data.date FROM data INNER JOIN player ON data.playerID = player.playerID WHERE player.playerID=%s ORDER BY date DESC',
         (LOGGEDIN_PLAYERID, ))
     result = self.cursor.fetchall()
     data = Convert(result)
     tframe = Frame(self.my_w)
     tframe.pack()
     model = TableModel()
     table = TableCanvas(tframe,
                         model=model,
                         data=data,
                         editable=False,
                         width=800,
                         height=300)
     table.show()
     self.my_w.mainloop()
Esempio n. 20
0
def display(event=None):
    print("file", file_name)
    recreate()
    if (file_name):
        """recreate()
        typ=re.search(r'.csv',file_name)
        if(typ==None):"""
        table = TableCanvas(f1, read_only=True)
        #for csv and xls file------------------------------
        table.importCSV(file_name)
        #print (self.table.model.columnNames)
        table.show()
        """else:
            table = tktable.Table(root, rows=10, cols=4)
            table.pack(side="top", fill="both", expand=True)"""
    else:

        msgbx.showwarning("error", "No File is selected")
Esempio n. 21
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        # Background Label
        self.bgImg = tk.PhotoImage(file='background.png')
        bgLabel = tk.Label(self, image=self.bgImg)
        bgLabel.place(relheight=1, relwidth=1, anchor='nw')

        # new frame to see data
        self.itemsListFrame = tk.Frame(self, bg='#b536aa')
        self.itemsListFrame.place(relx=0.15,
                                  rely=0.2,
                                  relheight=0.6,
                                  relwidth=0.7)

        model = TableModel()
        items = item_database.getData()
        print(len(items))
        data = {}

        for i in range(len(items)):
            data['row' + str(i + 1)] = {
                'Name': items[i][0],
                'Barcode': items[i][1],
                'P.Price': items[i][2],
                'S.Price': items[i][3],
                'Quantity': items[i][4]
            }

        table = TableCanvas(self.itemsListFrame, data=data)
        table.show()

        # Add a new frame for back button
        frame = tk.Frame(self, bg='#b536aa')
        frame.place(relx=0.15, rely=0.8, relheight=0.1, relwidth=0.7)

        # Add Back Button
        back_btn = tk.Button(
            frame,
            text='Back',
            font=('Courier', 15, 'bold'),
            command=lambda: controller.show_frame(InventoryPage))
        back_btn.place(relx=0.35, rely=0.3, relheight=0.3, relwidth=0.3)
    def __init__(self, parent=None):
        self.parent = parent
        Frame.__init__(self)
        self.main = self.master
        self.main.geometry('890x500')
        self.main.title('Pedidos')
        f = Frame(self.main)
        f.pack(fill=BOTH, expand=1)
        table = TableCanvas(f, editable=False)
        table.importCSV('test.csv')
        #print (table.model.columnNames)
        #table.model.data[1]['a'] = 'XX'
        #table.model.setValueAt('YY',0,2)
        table.show()
        return


#app=TestApp()
#app.mainloop()
Esempio n. 23
0
def tableFunc():
    tk = Tk()
    tk.geometry('800x500+200+100')
    tk.title('Test')
    f = Frame(tk)
    f.pack(fill=BOTH, expand=1)
    data = {}
    for i in range(0, 5):
        data[i] = {
            'col1': 99.88,
            'col2': 108.79,
            'label': 'rec1asdfasfasdfasdfasdfasdf'
        }
    table = TableCanvas(f, data=data)
    table.show()
    tk.mainloop()
    c = table.model.getRowCount()
    for i in range(0, c):
        print(table.model.getRecordAtRow(i))
    return
Esempio n. 24
0
 def muestradatos(self, event):
     model = TableModel()
     self.curs.execute(self.var_sql.get())
     output = self.curs.fetchall()  #output from query
     columns = [description[0] for description in self.curs.description]
     output_dict = {}
     for index in range(
             len(output)):  #use an index to create new dictionary elements
         data = output[
             index]  #use that index to find the next piece of data to insert into output dictionary
         dictrecord = {}
         for indcol in range(len(columns)):
             dictrecord[columns[indcol]] = data[indcol]
         output_dict[index] = dictrecord
         #create new dictionary element, using
         #the index as the key and setup a nested dictionary as the value associated with the key
     table = TableCanvas(self.frtab,
                         data=output_dict,
                         width=600,
                         height=300)
     table.show()
Esempio n. 25
0
 def SQL_ALTERNATIVE_display_leaderboard(self):
     '''
     display top 10 kills, by using sql limit
     then sort the list by using mergesort, with highest kill on top. Could have also used sql ORDER BY
     '''
     self.cursor.execute(
         'SELECT player.username, MAX(data.kills) AS kills, data.date FROM data INNER JOIN player ON data.playerID = player.playerID GROUP BY username ORDER BY data.kills DESC limit 0, 10 '
     )
     result = self.cursor.fetchall()
     data = Convert(result)
     tframe = Frame(self.my_w)
     tframe.pack()
     model = TableModel()
     table = TableCanvas(tframe,
                         model=model,
                         data=data,
                         editable=False,
                         width=800,
                         height=300)
     table.show()
     self.my_w.mainloop()
Esempio n. 26
0
def showDEsDescribedGRN(father, des):
    # column_names = ['Gene','Equation']
    # xx = tk.Scrollbar(father, orient="horizontal")
    # yy = tk.Scrollbar(father, orient="vertical")
    # table = ttk.Treeview(father, columns=tuple(column_names), xscrollcommand=xx.set, yscrollcommand=yy.set)
    # xx.pack(side="bottom", fill="x")
    # yy.pack(side="right", fill="y")
    # for name in column_names:
    #     table.heading(name, text=name)
    # table['show'] = 'headings'
    #
    # xx.config(command=table.xview)
    # yy.config(command=table.yview)
    #
    # table.column('Gene', width=70)
    # table.column('Equation', width=600)
    #
    # n_des=des.values.shape[0]
    # for k in range(n_des):
    #     table.insert('', k , text="", values=tuple(des.values[k]))

    # based on tktable developed
    data = odesdf2dict(des)
    xx = tk.Scrollbar(father, orient="horizontal")
    yy = tk.Scrollbar(father, orient="vertical")
    table = TableCanvas(father,
                        data=data,
                        cellwidth=200,
                        cellbackgr='#e3f698',
                        thefont=('Arial', 12),
                        rowheight=25,
                        rowheaderwidth=30,
                        rowselectedcolor='yellow',
                        read_only=False,
                        width=20,
                        xscrollcommand=xx.set,
                        yscrollcommand=yy.set)

    table.show()
    return table
Esempio n. 27
0
 def _table_show(self, infos):
     tk = Tk()
     tk.geometry('800x500+200+100')
     tk.title('Test')
     f = Frame(tk)
     f.pack(fill=BOTH, expand=1)
     data = {}
     for i, val in enumerate(infos):
         tmp_data = {}
         for hi, hv in enumerate(head):
             tmp_data[hv] = val[hi]
         data[i] = tmp_data
     table = TableCanvas(f, data=data)
     table.show()
     tk.mainloop()
     c = table.model.getRowCount()
     new_infos = []
     for i in range(0, c):
         tmp = table.model.getRecordAtRow(i)
         tmp_info = []
         for hi, hv in enumerate(head):
             tmp_info.append(tmp[hv])
         new_infos.append(tmp_info)
     return new_infos
Esempio n. 28
0
class Table:
    '''
    Excel-like table in tkinter gui
    '''
    def __init__(self, master, columns):

        # default params
        self.params = {
            'cellwidth': 110,
            'precision': 6,
        }

        self.data = []

        self.model = TableModel()
        self.columns = columns
        for column in columns:
            self.model.addColumn(colname=column)
        self.table = TableCanvas(parent=master, model=self.model, cellwidth=self.params['cellwidth'], read_only=True)
        self.table.setSelectedRow(-1)
        self.table.show()
        
        self.n_rows = 0

    def set_params(self, params):
        assert params.keys() == self.params.keys()
        self.params = params
        self.table.cellwidth = self.params['cellwidth']
        self.refresh()

    def get_params(self):
        return self.params.copy()

    def _process_val(self, val):
        if val is None:
            return 'N/A'
        elif isinstance(val, bool):
            if val == True: return 'True'
            else: return 'False'
        elif isinstance(val, float):
            if np.isnan(val): return 'N/A'
            else: return round(val, self.params['precision'])
        else:
            return str(val)

    def transform_data(self, data_list):
        '''
        '''
        new_data_list = []
        for data in data_list:
            data = np.array(data, dtype=str)
            if len(data.shape) == 1:
                data = np.expand_dims(data, axis=1)
            assert len(data.shape) == 2
            new_data_list.append(data)
        return np.hstack(new_data_list)

    def load(self, data, transform=False):
        '''
        '''
        if transform:
            data = self.transform_data(data)

        if len(data) > self.n_rows:
            self.model.autoAddRows(len(data) - self.n_rows)
            self.data.extend([[None for _ in self.columns] for _ in range(len(data) - self.n_rows)])
        elif len(data) < self.n_rows:
            self.model.deleteRows(rowlist=range(len(data), self.n_rows))
            del self.data[len(data):]
        self.n_rows = len(data)

        for row in range(self.n_rows):
            row_data = data[row]
            for j, col in enumerate(self.columns):
                self.model.data[row][col] = self._process_val(row_data[j])
                self.data[row][self.columns.index(col)] = row_data[j]

        self.table.redrawTable()

    def insert(self, columns, data, transform=False):
        '''
        Insert data into bottom of the table
        '''
        if transform:
            data = self.transform_data(data)

        old_n_rows = self.n_rows
        if len(data) > 0:
            self.model.autoAddRows(len(data))
            self.data.extend([[None for _ in self.columns] for _ in data])
            self.n_rows = old_n_rows + len(data)

        if columns is None: columns = self.columns

        for i, row in enumerate(range(old_n_rows, self.n_rows)):
            row_data = data[i]
            for j, col in enumerate(columns):
                self.model.data[row][col] = self._process_val(row_data[j])
                self.data[row][self.columns.index(col)] = row_data[j]
        
        self.table.redrawTable()

    def update(self, columns, data, rowids=None, transform=False):
        '''
        Update rows of the table (TODO: support single rowid)
        '''
        if transform:
            data = self.transform_data(data)

        if rowids is None:
            rowids = list(range(len(data)))
            new_n_rows = len(data)
            if new_n_rows > self.n_rows:
                self.model.autoAddRows(new_n_rows - self.n_rows)
                self.n_rows = new_n_rows

        if columns is None: columns = self.columns

        assert len(data) == len(rowids)
        for i, row in enumerate(rowids):
            row_data = data[i]
            for j, col in enumerate(columns):
                self.model.data[row][col] = self._process_val(row_data[j])
                self.data[row][self.columns.index(col)] = row_data[j]

        self.table.redrawTable()

    def refresh(self):
        '''
        '''
        for row in range(self.n_rows):
            for j, col in enumerate(self.columns):
                self.model.data[row][col] = self._process_val(self.data[row][j])
        
        self.table.redrawTable()

    def get(self, row, column):
        '''
        Get the cell value
        '''
        return self.table.model.data[row][column]

    def get_column(self, column):
        '''
        Get values of a column
        '''
        return [self.get(row, column) for row in range(self.n_rows)]

    def export_csv(self):
        '''
        Export table content to a csv file
        '''
        self.table.exportTable()
Esempio n. 29
0
class StockPage(ttk.Frame):
    def __init__(self, parent, controller):
        ttk.Frame.__init__(self, parent)

        self.controller = controller
        # Center your Frame in the middele-top.
        self.columnconfigure(1, weight=1)

        # Set the widget's background.
        self["style"] = "Background.TFrame"

        # Add some buttons.
        button_1 = ttk.Button(
            self,
            text="Add New Product",
            command=lambda: controller.show_frame("AddNewProd"),
            width=19,
            style="Background.TButton")
        button_1.grid(row=0, column=0, padx=(70, 10), pady=8, sticky="E")

        button_2 = ttk.Button(
            self,
            text="Delete Product",
            command=lambda: controller.show_frame("DeleteProd"),
            width=19,
            style="Background.TButton")
        button_2.grid(row=0, column=1, pady=8, sticky="W")

        go_back_button = ttk.Button(
            self,
            text="BACK",
            command=lambda: controller.show_frame("StartPage"),
            width=5,
            style="BackButton.TButton")
        go_back_button.grid(row=0, column=3, padx=8, pady=8, sticky="NE")

    def focus_on_entry(self):
        pass

    def redraw_tables(self):
        try:
            # The data from th API.
            request = requests.get("http://127.0.0.1:8000/products/",
                                   auth=("gabriel", "1"))

            # Transform the API's data to the TableCanvas' form.
            # Use the unique index for the rows in the TableCanvas.
            data = {}
            for i in request.json():
                data[request.json().index(i)] = i

            # Create a new frame for the TableCanvas.
            tframe = ttk.Frame(self)
            tframe.grid(row=1, columnspan=4, padx=10, pady=10)
            self.table = TableCanvas(
                tframe,
                data=data,
                read_only=True,
                width=1300,
                height=600,
                cellwidth=325,
                rowheight=40,
                rowheaderwidth=60,  # To hide; set value to 0.
                rowselectedcolor=None,  # Get rid of the row selection.
                selectedcolor=None,  # Get rid of the cell selection.
                thefont=('Arial', 15),
            )
            self.table.show()
        except:
            messagebox.showerror("API Error", "The api isn't running.")
Esempio n. 30
0
class EventMaker(tk.Frame):
    def __init__(self, section_name, master=None, model_name=None, **options):
        """
        Frames parameter section inquiries as listed in cEvents.ModelEvents
        :param section_name: STR of section name - must be one of: "bce", "..."
        :param master: tk.Frame-master
        :param options: relief, ...
        """
        Frame.__init__(self, master, **options)
        if not model_name:
            self.mbce = cTFmodel.Hy2OptModel("default")
        else:
            self.mbce = cTFmodel.Hy2OptModel(model_name)
            self.mbce.overwrite_defaults(section_name)
        self.sn = section_name
        self.number_of_events = 1
        self.del_event_var = tk.StringVar()

        self.bg_color = self.mbce.bce_bg_colors[self.sn]
        self.config(width=ww, height=int(20 * self.mbce.default_dicts[self.sn].keys().__len__()), bg=self.bg_color)
        tk.Label(self, text=self.mbce.bce_name_dict[self.sn].upper()).grid(sticky=tk.W, row=0, column=0, columnspan=3, padx=xd, pady=yd)

        usr_msg, fg_col = self.chk_model()
        self.l_model_check = tk.Label(self, fg=fg_col, width=85, text=usr_msg)
        self.l_model_check.grid(sticky=tk.W, row=1, column=0, columnspan=3, padx=xd, pady=yd)

        self.par_objects = {"Events": self.mbce.event_file}
        if os.path.isfile(dir2tf + "models/" + self.mbce.event_file[0]):
            self.mbce.events = fGl.dict_nested_read_from_file(dir2tf + "models/" + self.mbce.event_file[0])

        self.table_frame = Frame(self, width=700)
        self.table_frame.grid(sticky=tk.EW, row=2, rowspan=2, column=0, columnspan=3, padx=xd, pady=yd)
        self.table = TableCanvas(self.table_frame, data=self.mbce.events)
        if model_name and self.mbce.events:
            self.table.show()

        tk.Button(self, text="Add event", command=lambda: self.add_row()).grid(sticky=tk.EW, row=2, column=3, padx=xd, pady=yd)
        tk.Button(self, text="Delete event\n(row) No:", command=lambda: self.del_row()).grid(sticky=tk.EW, row=3, column=3, padx=xd, pady=yd)
        tk.Entry(self, width=3, textvariable=self.del_event_var).grid(sticky=tk.EW, row=3, column=4, padx=xd, pady=yd)

        self.make_up()

    def add_row(self):
        self.number_of_events += 1
        self.table.addRow(self.number_of_events)

    def del_row(self):
        self.number_of_events -= 1
        try:
            del_row = int(self.del_event_var.get()) - 1
            self.table.setSelectedRow(del_row)
            self.table.deleteRow()
        except:
            showinfo("INFO", "The event number must be a positive integer of a present row number.", parent=self)
            return -1

        if self.number_of_events < 1:
            showinfo("WARNING", "Define at least one event!", parent=self)

    def chk_model(self):
        if not (self.mbce.name == "default"):
            msg0 = "Define inlet flows (for Name-fields of 2d_sa_MODEL_QT_R.shp)\nand outlet WSEs (for Name-fields of 2d_bc_MODEL_HT.shp).\n"
            self.mbce.get_boundary_sa_names()
            self.mbce.get_boundary_bc_names()
            msg1 = str("Identified inlet names: " + ", ".join(self.mbce.bc_dict['sa']))
            msg2 = str("\nIdentified outlet names: " + ", ".join(self.mbce.bc_dict['bc']))
            return msg0 + msg1 + msg2, "forest green"
        else:
            msg0 = "NOT AVAILABLE\n\nDefine and select a model.\n"
            msg1 = "Event definitions require the prior definition of a mode with a 2d_sa_MODEL_QT_R.shp file (Geometry Tab)."
            return msg0 + msg1, "red3"

    def make_up(self):
        for wid in self.winfo_children():
            try:
                wid.configure(bg=self.bg_color)
            except:
                pass

    def save_event_file(self):
        self.mbce.events = {}  # reset events dictionary

        for row in range(1, self.table.rows+1):
            self.mbce.events.update({row: {}})
            for col in self.table.model.columnNames:
                try:
                    self.mbce.events[row].update({col: self.table.model.data[row][col]})
                except:
                    print("Setting %s to 0.0 (no value defined)" % str(col))
                    self.mbce.events[row].update({col: 0.0})

        fGl.dict_nested_write2file(self.mbce.events, dir2tf + "models/" + self.mbce.event_file[0])