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
def MenuAssignments(): AssignmentsWindow = tk.Toplevel(window) AssignmentsWindow.title("Replenisher Assignments") AssignmentsWindow.geometry('800x500') UserList = [ "User Selection", "User1", "User2", "User3" ] UserVariable = StringVar(AssignmentsWindow) UserVariable.set(UserList[0]) # default value UserOptionMenu = tk.OptionMenu(AssignmentsWindow, UserVariable, *UserList) UserOptionMenu.pack() TaskList = [ "Task Selection", "Task1", "Task2", "Task3" ] TaskVariable = StringVar(AssignmentsWindow) TaskVariable.set(TaskList[0]) # default value TaskOptionMenu = tk.OptionMenu(AssignmentsWindow, TaskVariable, *TaskList) TaskOptionMenu.pack() def AddUserTask(): tkMessageBox.showinfo('Add User and Task', "Added User: "******"; " + "Added Task: " + TaskVariable.get() ) AddUserTaskBT = tk.Button(AssignmentsWindow, text="Add User and Task", command=AddUserTask) AddUserTaskBT.pack() #Add a table ''' RowNum = 2 ColNum = 2 for i in range(RowNum): for j in range(ColNum): b = tk.Entry(AssignmentsWindow, text="") b.grid(row=i, column=j) b.pack() ''' #To use tkintertable tframe = tk.Frame(AssignmentsWindow) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) table.createTableFrame() model = table.model data = {'rec1': {'User': '******', 'Task': 'Task1', 'Status': 'Open', 'Rank': 1, 'Priority': 'High', 'Start Time': '05-19-2018 10:30', 'Finish Time': ''}, 'rec2': {'User': '******', 'Task': 'Task2', 'Status': 'Open', 'Rank': 2, 'Priority': 'Low', 'Start Time': '05-19-2018 11:30', 'Finish Time': '05-19-2018 22:30'}, 'rec3': {'User': '******', 'Task': 'Task3', 'Status': 'Open', 'Rank': 3, 'Priority': 'Low', 'Start Time': '05-19-2018 12:30', 'Finish Time': '05-19-2018 22:45'} } model.importDict(data) #Import from a dictionary to populate model table.redrawTable() AssignmentsWindow.mainloop()
def demo2(root): frame = Frame(root) frame.pack() model = TableModel() model.importDict(data) table = TableCanvas(frame, model=model) table.createTableFrame()
def classify_handler(self): # Show Classification waiting window wdw = Tkinter.Toplevel() wdw.title('Classification Results ' + self.dropdown_value.get()) Tkinter.Label(wdw, text="Classification in Progress... Please wait", font=("Helvetica", 12), width=50, fg="blue").pack() wdw.update() wdw.deiconify() # Predict and load results resultModel = TableModel() resultDict = speakerclassifier.classify_audio(self.currentFile, self.dropdown_value.get()) if len(resultDict) > 0 : resultModel.importDict(resultDict) wdw.destroy() if len(resultDict) > 0 : # Show Classification results in modal table window wdw = Tkinter.Toplevel() wdw.geometry('350x200+200+200') wdw.title('Classification Results ' + self.dropdown_value.get()) tframe = Tkinter.Frame(wdw) tframe.pack() table = TableCanvas(tframe, model=resultModel, editable=False) table.createTableFrame() table.sortTable(columnName='Score (%)', reverse=True) wdw.transient(self.root) wdw.grab_set() self.root.wait_window(wdw) else : tkMessageBox.showerror('Classification Results', 'There are currently no users in the System')
def _drawMe(self,dir,openColumn): model = TableModel() for c in self.items.columnNames: model.addColumn(c) model.importDict(self.items.columnValues) self.table = ActionableTableCanvas(self, model=model, rowheaderwidth=140, showkeynamesinheader=True,height=125,openColumn=openColumn,dir=dir) self.table.updateModel(model) self.table.createTableFrame()
def demo3(root): frame = Frame(root) frame.pack() model = TableModel() model.importDict(data) table = TableCanvas(frame, model=model) table.createTableFrame() table.model.data['rec2']['col2'] = 50 table.redrawTable()
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 _drawMe(self): model = TableModel() for c in self.items.getColumnNames(self.section): model.addColumn(c) model.importDict(self.items.toColumns(self.section)) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.table = ActionableTableCanvas(self, model=model, rowheaderwidth=140, showkeynamesinheader=True,height=125) self.table.updateModel(model) self.table.createTableFrame()
def demo4(root): frame = Frame(root) frame.pack() model = TableModel() model.importDict(data) table = TableCanvas(frame, model=model, rowheaderwidth=0, cellwidth=150, rowheight=20, editable=False, rowselectedcolor='red', reverseorder=1) table.createTableFrame()
def drawEnemyFleetTable(self): self.model = TableModel() self.table = TableCanvas(self.EnemyFleet, model=self.model, cellwidth=50, cellbackgr='white', thefont=self.tkFont, rowheight=16, editable=True, rowselectedcolor='white', reverseorder=1) self.table.createTableFrame() self.table.model.columnNames = ['A', 'B', 'C', 'D', 'E'] self.table.redrawTable self.iniEnemyFleet()
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()
def initFrame(self): # *****界面区***** # 布局参数 params = ['row','column','rowspan','columnspan'] gridMap = {'label':(0,0), 'entry':(0,1), 'search_button':(0,2), 'table':(1,1,None,3), 'next_page':(2,1), 'modify':(2,2), 'corfirm':(2,3)} cnfs = {} for k,vals in gridMap.items(): dic = {} for i,v in enumerate(vals): dic[params[i]] = v cnfs[k] = dic ttk.Label(self, text='搜索', style="BW.TLabel").grid(cnfs['label']) self.keyword = tk.StringVar() # 搜索框 tk.Entry(self, borderwidth=3, width=40, textvariable=self.keyword, selectbackground='gray').grid(cnfs['entry']) ttk.Button(self, text='搜索', command="", width=9).grid(cnfs['search_button']) frame = tk.Frame(self) frame.grid(cnfs['table']) model = TableModel() self.table = TableCanvas(frame,model) self.table.show() ttk.Button(self, text='下一页', command="", width=9).grid(cnfs['next_page']) ttk.Button(self, text='设为组合', command=self.set_combo, width=9).grid(cnfs['next_page'],sticky=tk.E) ttk.Button(self, text='修改', command=self.modify, width=9).grid(cnfs['modify']) ttk.Button(self, text='选择', command=self.choic, width=9).grid(cnfs['corfirm'])
def loginto(): aa= MySQLdb.connect(host='127.0.0.1',port= 3306,user="******",passwd="010905885",db="kitpage") mm = aa.cursor() username = e1.get() password = e2.get() mm.execute('SELECT * FROM singup WHERE username = %s AND passwords = %s', (username, password)) for i in username: print i if mm.fetchall(): tkMessageBox.showinfo("Welcome to %s" %username, "Let GO") R.destroy() master = Tk() tframe = Frame(master) tframe.pack() table = TableCanvas(tframe) table.createTableFrame() model = TableModel()adf table = TableCanvas(tframe, model=model) master.mainloop() else: tkMessageBox.showinfo("Sorry" , "Wrong Password")
def iniEnemyFleet(self): self.model = TableModel() self.table = TableCanvas(self.EnemyFleet, model=self.model, cellwidth=106, cellbackgr='white', thefont=self.tkFont, rowheight=106, editable=True, rowselectedcolor="white", reverseorder=1, align='center') self.model.importDict(self.enemyFleetDict) self.table.createTableFrame() self.table.autoResizeColumns() self.table.redrawTable
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 __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()
def viewFreqOutput(event): top = Toplevel() analysis = {} f = open("frequency_output.txt") for line in f: record = {} tokens = line.rstrip('\n').split(' ') if tokens[0] not in analysis: record["Label"] = tokens[0] record["Frequency"] = tokens[1] analysis[tokens[0]] = record # print(analysis) model = TableModel() model.importDict(analysis) table = TableCanvas(top, model=model) table.createTableFrame() top.mainloop()
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 DataGrid(xValues, yValues): ## setup window dataGrid = Tk() dataGrid.wm_title("Data") ## setup frame frame = Frame(dataGrid) frame.pack() label = Label(dataGrid, text=("Showing %.0f data points" % len(xValues)), font=("Verdana", 12)) label.pack(pady=5, padx=10) dataDict = {} ## iterate through time for i in range(0, len(xValues)): xVal = ("%.2f" % float(xValues[i])) yVal = ("%.2f" % float(yValues[i])) dataDict[xVal] = {"Time (s)": xVal, "Height (m)": yVal} model = TableModel() model.importDict(dataDict) model.moveColumn(model.getColumnIndex('Time (s)'), 0) table = TableCanvas(frame, model=model, editable=False) table.createTableFrame() ## order by time table.sortTable(columnName='Time (s)') dataGrid.mainloop()
def ClearTable(): DataTracking.Question = [] DataTracking.Answers = [] DataTracking.Correct = [] Data = {} model = TableModel() table = TableCanvas(tframe, data=Data) table.show()
def MenuTask(): TaskWindow = tk.Toplevel(window) TaskWindow.title("Add New Tasks") TaskWindow.geometry('800x500') TaskList = [ "Add Task" ] TaskVariable = StringVar(TaskWindow) TaskVariable.set(TaskList[0]) # default value TaskOptionMenu = tk.OptionMenu(TaskWindow, TaskVariable, *TaskList) TaskOptionMenu.pack() def AddTask(): tkMessageBox.showinfo('WLabs Replenisher', 'Successfully Add New Task') AddTaskBT = tk.Button(TaskWindow, text="Add Task", command=AddTask) AddTaskBT.pack() #To use tkintertable tframe = tk.Frame(TaskWindow) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) table.createTableFrame() model = table.model data = {'rec1': {'ID': 'Task1', 'Priority': 'High' }, 'rec2': {'ID': 'Task2', 'Priority': 'Low' }, 'rec3': {'ID': 'Task3', 'Priority': 'Low' } } model.importDict(data) #Import from a dictionary to populate model table.redrawTable() #Add New Row button def AddRowButton(): table.addRow() table.redrawTable() AddRowBTN = tk.Button(TaskWindow,text='Add New Row', command = AddRowButton) AddRowBTN.place(relx=0.9, rely=0.15, anchor=tk.CENTER) TaskWindow.mainloop()
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 MenuUser(): UserWindow = tk.Toplevel(window) UserWindow.title("Add New User") UserWindow.geometry('800x500') UserList = [ "Add User" ] UserVariable = StringVar(UserWindow) UserVariable.set(UserList[0]) # default value UserOptionMenu = tk.OptionMenu(UserWindow, UserVariable, *UserList) UserOptionMenu.pack() def AddUser(): tkMessageBox.showinfo('WLabs Replenisher', 'Successfully Add New User') AddUserBT = tk.Button(UserWindow, text="Add User", command=AddUser) AddUserBT.pack() #To use tkintertable tframe = tk.Frame(UserWindow) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) table.createTableFrame() model = table.model data = {'rec1': {'ID': 'User1', 'First Name': 'Tom', 'Last Name': 'Cross' }, 'rec2': {'ID': 'User2', 'First Name': 'Jim', 'Last Name': 'Wood' }, 'rec3': {'ID': 'User3', 'First Name': 'Bryan', 'Last Name': 'Bush' } } model.importDict(data) #Import from a dictionary to populate model table.redrawTable() #Add New Row button def AddRowButton(): table.addRow() table.redrawTable() AddRowBTN = tk.Button(UserWindow,text='Add New Row', command = AddRowButton) AddRowBTN.place(relx=0.9, rely=0.15, anchor=tk.CENTER) UserWindow.mainloop()
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()
def DataGrid(xValues, yValues): ## setup window dataGrid = Tk() dataGrid.wm_title("Data") ## setup frame frame = Frame(dataGrid) frame.pack() label = Label(dataGrid, text=("Showing %.0f data points" % len(xValues)), font=("Verdana", 12)) label.pack(pady=5, padx=10) dataDict = {} ## iterate through time for i in range(0, len(xValues)): xVal = "%.2f" % float(xValues[i]) yVal = "%.2f" % float(yValues[i]) dataDict[xVal] = {"Time (s)": xVal, "Height (m)": yVal} model = TableModel() model.importDict(dataDict) model.moveColumn(model.getColumnIndex("Time (s)"), 0) table = TableCanvas(frame, model=model, editable=False) table.createTableFrame() ## order by time table.sortTable(columnName="Time (s)") dataGrid.mainloop()
def classify_handler(self): # Show Classification waiting window wdw = Tkinter.Toplevel() wdw.title('Classification Results ' + self.dropdown_value.get()) Tkinter.Label(wdw, text="Classification in Progress... Please wait", font=("Helvetica", 12), width=50, fg="blue").pack() wdw.update() wdw.deiconify() # Predict and load results resultModel = TableModel() resultDict = speakerclassifier.classify_audio( self.currentFile, self.dropdown_value.get()) if len(resultDict) > 0: resultModel.importDict(resultDict) wdw.destroy() if len(resultDict) > 0: # Show Classification results in modal table window wdw = Tkinter.Toplevel() wdw.geometry('350x200+200+200') wdw.title('Classification Results ' + self.dropdown_value.get()) tframe = Tkinter.Frame(wdw) tframe.pack() table = TableCanvas(tframe, model=resultModel, editable=False) table.createTableFrame() table.sortTable(columnName='Score (%)', reverse=True) wdw.transient(self.root) wdw.grab_set() self.root.wait_window(wdw) else: tkMessageBox.showerror( 'Classification Results', 'There are currently no users in the System')
def populateData(type): top = Toplevel() analysis = {} if type == "LDA": with open("./analysis/LDA_output.txt") as f: next(f) index = 0 for line in f: tokens = line.rstrip('\n').split(':') topicWords = tokens[1].split('+') print(topicWords) for w in topicWords: record = {} tw = w.split('*') record["Topic ID"] = tokens[0] record["Probability"] = tw[0] word = tw[1].replace('"', '').replace('"', '') record["Word"] = word analysis[index] = record index = index + 1 else: with open("./analysis/LSI_output.txt") as f: next(f) index = 0 for line in f: record = {} tokens = line.rstrip('\n').split(':') record["Document Name"] = tokens[0] record["Document ID"] = tokens[1] record["Probability"] = tokens[2] analysis[index] = record index = index + 1 model = TableModel() model.importDict(analysis) table = TableCanvas(top, model=model) table.createTableFrame() top.mainloop()
def submit(*value): print('_____________________________________________________________') model = TableModel() # load data data = load_data(name, value) # import data to tablemodel model.importDict(data) # Create table for records preview table = TableCanvas(recordsFrame, name="tablica", model=model, width=420, height=600, cols=0, rows=0, cellwidth=50, editable=False, showkeynamesinheader=True, reverseorder=0) table.grid(row=0, sticky=W + N + S) table.createTableFrame() table.redrawTable()
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()
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 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()
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()
def loadAfllictTable(self): global showingTables afflicDataTableModel = TableModel() if debug: afflicDataTableModel.importCSV("D:\\TAMS Stuff\\TAMS Research\\Dr. Chyan Lab\\TAMS Summer Research 2020\\MEDA\\FPS Testing\\Sample 1 TI Device\\S1 Reg B\\Results\\15FPM\\0.25FPS AfflictData.csv", sep=",") else: print(directory + "/" + str(fps) + "FPS AfflictData.csv") afflicDataTableModel.importCSV(directory + "/" + str(fps) + "FPS AfflictData.csv") self.afflictTable = TableCanvas(self.FAfflictTable, model=afflicDataTableModel, rowheaderwidth=0, read_only=True, cols=3, height=865, width=384) self.afflictTable.cellwidth=121 self.afflictTable.maxcellwidth=121 self.afflictTable.grid(column=0, row=0, sticky="NSW") self.afflictTable.show() self.afflictTable.resizeColumn(0, 82) self.afflictTable.resizeColumn(1, 123) self.afflictTable.resizeColumn(2, 178) self.showAfflictTable()
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()
def quitarListado(self,numero): voluntario = self.selectTable.model.getRecordAtRow(numero) modelNuevo = TableModel() modelNuevo.addColumn("nombre") modelNuevo.addColumn("apellidos") modelNuevo.addColumn("dni") modelNuevo.addColumn("direccion") modelNuevo.addColumn("correo_electronico") modelNuevo.addColumn("estudio") modelNuevo.addColumn("parroquial") modelNuevo.addColumn("proyecto") modelNuevo.addColumn("genero") modelNuevo.addColumn("fecha_nacimiento") modelNuevo.addColumn("telefono_1") modelNuevo.addColumn("telefono_2") print numero arrayListado = self.selectTable.getModel().data valores = {} i=1 for values in arrayListado: if numero+1 != i: valores['row',i]=arrayListado['row',i] i+=1 modelNuevo.importDict(valores) self.selectTable.updateModel(modelNuevo) self.selectTable.redrawTable()
def buscar(self,nombre,apellidos): modelCompleto = TableModel() modelNuevo = TableModel() modelNuevo.addColumn("nombre") modelNuevo.addColumn("apellidos") modelNuevo.addColumn("dni") modelNuevo.addColumn("direccion") modelNuevo.addColumn("correo_electronico") modelNuevo.addColumn("estudio") modelNuevo.addColumn("parroquial") modelNuevo.addColumn("proyecto") modelNuevo.addColumn("genero") modelNuevo.addColumn("fecha_nacimiento") modelNuevo.addColumn("telefono_1") modelNuevo.addColumn("telefono_2") self.listilla= queryAllVoluntarios() modelCompleto.importDict(self.listilla) searchterms = [('nombre', nombre, 'contains', 'AND'),('apellidos', apellidos, 'contains', 'AND')] result=modelCompleto.getDict(modelCompleto.columnNames, filters=searchterms) modelNuevo.importDict(result) self.listadoSeleccionado = result self.table.updateModel(modelNuevo) self.table.redrawTable()
def initUI(self): self.parent.title("Caritas") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) frameMenu = Frame(self) frameMenu.pack(fill="both", expand="0", side=RIGHT) labelBusqueda = LabelFrame(frameMenu, text="Busqueda") labelBusqueda.pack(fill="x",expand =1) labelVoluntarios = LabelFrame(frameMenu) labelVoluntarios.pack(fill="both",expand =0) frameTabla = Frame(self) frameTabla.pack(fill="both", expand="1", side=LEFT) labelTabla = LabelFrame(frameTabla) labelTabla.pack(fill="both", expand="1") labelBotonera = LabelFrame(frameTabla) labelTabla.pack(fill="both", expand="1") labelSelect = LabelFrame(frameTabla) labelSelect.pack(fill="both", expand="1") model = TableModel() modelSelect = TableModel() model.addColumn("nombre") model.addColumn("apellidos") model.addColumn("dni") model.addColumn("direccion") model.addColumn("correo_electronico") model.addColumn("estudio") model.addColumn("parroquial") model.addColumn("proyecto") model.addColumn("genero") model.addColumn("fecha_nacimiento") model.addColumn("telefono_1") model.addColumn("telefono_2") modelSelect.addColumn("nombre") modelSelect.addColumn("apellidos") modelSelect.addColumn("dni") modelSelect.addColumn("direccion") modelSelect.addColumn("correo_electronico") modelSelect.addColumn("estudio") modelSelect.addColumn("parroquial") modelSelect.addColumn("proyecto") modelSelect.addColumn("genero") modelSelect.addColumn("fecha_nacimiento") modelSelect.addColumn("telefono_1") modelSelect.addColumn("telefono_2") #Tabla Voluntarios self.listilla= queryAllVoluntarios() model.importDict(self.listilla) self.table = TableCanvas(labelTabla, model=model,editable=False) self.table.createTableFrame() self.table.handle_double_click(self.eventoClic) #Tabla Seleccionados self.selectTable = TableCanvas(labelSelect, model=modelSelect,editable=False) self.selectTable.createTableFrame() self.listadoSeleccionado = [] L1 = Label(labelBusqueda, text="Nombre") L1.pack() E1 = Entry(labelBusqueda) E1.pack() L2 = Label(labelBusqueda, text="Apellidos") L2.pack() E2 = Entry(labelBusqueda) E2.pack() botonArriba = Button(labelVoluntarios, text="Agregar al listado", command=lambda:self.agregarListado(self.table.getSelectedRow())) botonArriba.pack() botonAbajo = Button(labelVoluntarios, text="Quitar del listado", command=lambda:self.quitarListado(self.selectTable.getSelectedRow())) botonAbajo.pack() button = Button(labelBusqueda, text="Buscar", command=lambda: self.buscar(E1.get(),E2.get())) button.pack() button = Button(labelVoluntarios, text="Nuevo Voluntario", command=lambda:self.ventanaVoluntarios(-1)) button.pack() buttonEditar = Button(labelVoluntarios, text="Editar Voluntario", command=lambda:self.ventanaVoluntarios(self.table.getSelectedRow())) buttonEditar.pack() buttonImprimir = Button(labelVoluntarios, text="Imprimir", command=lambda:self.ventanaImprimir()) buttonImprimir.pack()