class App: def __init__(self, tframe=None,\ d={1:{'col1':1.,'col2':'cell_1,2','col3':'cell_1,3'},2:{'col1':2.,'col2':'cell_2,2','col3':'cell_2,3'}}): self.tframe,self.d = tframe,d if tframe != None: tframe.pack(fill=BOTH) self.tmodel = TableModel() self.make_table_dataset(d) self.create_table() def make_table_dataset(self,d): '''d format: {row0: {col_name0: @R,C:contents, col_name1: @R,C:contents,...}, {row1: {col_name0:@R,C:contents, col_name1: @R,C:contents,...}, ..... for example: d = {1: {'date': 1189774539.345525, 'message': 'Commiting project ', 'author': 'damien'}, 2: {'date': 1189776100.545814, 'message': 'tommytest1', 'author': 'tc'}, 3: {'date': 1189776148.873471, 'message': 'test', 'author': 'elisa'}, 4: {'date': 1189776217.082571, 'message': "barbara's wt and mutant", 'author': 'btconnolly'}, 5: {'date': 1189776969.9782951, 'message': 'Adding a column', 'author': 'nielsen'}, 6: {'date': 1189777126.719934, 'message': 'fergal_test', 'author': 'fomeara'}, 7: {'date': 1189777948.4796059, 'message': 'TEST', 'author': 'elisa'}, 8: {'date': 1189778073.3868899, 'message': 'Adding 7TLN and deleting damen wt', 'author': 'nielsen'}, 9: {'date': 1189778472.5035281, 'message': 'Adding exp. data', 'author': 'nielsen'}, 10: {'date': 1189778553.6663699, 'message': 'Adding NMR tirtaion curve', 'author': 'nielsen'}, 11: {'date': 1189778701.032536, 'message': 'blaah', 'author': 'nielsen'}}''' self.tmodel.importDict(d) def create_table(self): self.table = TableCanvas(self.tframe, self.tmodel) self.table.createTableFrame() return
def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_pers_suc"), typedata='percent', align='right', max_val=u"100.0 %") self.model_ru_en.add_column(_("clm_state"), typedata='text', align='left', max_val=_("st_study") + u" ") for row in statistic.get_ru_en(): self.model_ru_en.add_row(row) self.model_ru_en.sort(6, False) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_pers_suc"), typedata='percent', align='right') self.model_en_ru.add_column(_("clm_state"), typedata='text', align='left') for row in statistic.get_en_ru(): self.model_en_ru.add_row(row) self.model_en_ru.sort(6, False) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width
def drawTable(data,frame) : model = TableModel() model.importDict(data) model.columnNames = ['UID','refType','Title','Authors','Journal','Year','Tags'] table = TableCanvas(frame, model=model) table.createTableFrame() table.redrawTable()
class tableView(ttk.Frame): #-----------------------------------------------------# def __init__(self, parent, db, tableName="Leer"): ttk.Frame.__init__(self, parent) self.model = TableModel() self.table = TableCanvas(self, model=self.model) self.pack(fill=tk.BOTH, expand=1) self.table.createTableFrame() if tableName == "Leer": return conn = sqlite3.connect(db) c = conn.cursor() c.execute("PRAGMA table_info(%s)" % tableName) # now create the model data = {} result = c.fetchall() colnames = [] for r in result: colnames.append(r[1]) c.execute("SELECT * from %s" % tableName) rows = c.fetchall() n = 0 for n in range(len(rows)): data[n] = {} data[n]["label"] = n count = 0 for r in rows[n]: data[n][colnames[count]] = r count += 1 self.model.importDict(data) self.table.redrawTable()
def __init__(self, tframe=None,\ d={1:{'col1':1.,'col2':'cell_1,2','col3':'cell_1,3'},2:{'col1':2.,'col2':'cell_2,2','col3':'cell_2,3'}}): self.tframe,self.d = tframe,d if tframe != None: tframe.pack(fill=BOTH) self.tmodel = TableModel() self.make_table_dataset(d) self.create_table()
def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.model = TableModel() self.table = TableCanvas(self, model=self.model) self.table.createTableFrame() root.bind('<ButtonRelease-1>', self.clicked) #Bind the click release event self.create_widgets()
def __init__(self, master,data=None,columns=None, upperColumnHeaders=None,**kw): ttk.Frame.__init__(self,master) self.tmodel = TableModel() if data!=None: self.tmodel.importDict(data,None,columns) self.table = self.create_table(self.tmodel,upperColumnHeaders,**kw) self.table.createTableFrame() return
def genRandomWebLogs(self): """ Method for generating random web log data. """ self.count += 1 if self.randomWebLogsWindowOpenedFlag == False: self.randomWebLogsWindowOpenedFlag = True # set window opened global RandomWebLogsWindow def toggleFlag(): self.randomWebLogsWindowOpenedFlag = False # set window closed RandomWebLogsWindow.destroy() RandomWebLogsWindow = tk.Toplevel(self) RandomWebLogsWindow.minsize(300, 500) RandomWebLogsWindow.geometry("300x500+100+100") RandomWebLogsWindow.title("Random web log data") RandomWebLogsWindow.config(bd=5) RandomWebLogsWindow.protocol("WM_DELETE_WINDOW", toggleFlag) x = sp.arange(1, 31 * 24) # 1 month of traffic data y = sp.array(200 * (sp.sin(2 * sp.pi * x / (7 * 24))), dtype=int) y += gamma.rvs(15, loc=0, scale=100, size=len(x)) y += 2 * sp.exp(x / 100.0) y = sp.ma.array(y, mask=[y < 0]) sp.savetxt(os.path.join("sample_data", "sample_web_traffic.tsv"), list(zip(x, y)), delimiter="\t", fmt="%s") model = TableModel() # create a new TableModel for table data table = TableCanvas(RandomWebLogsWindow, model=model, editable=False) # create a new TableCanvas for showing the table table.createTableFrame() tableData = {} # dictionary for storing table data for k, v in list(zip(x,y)): tableData[uuid.uuid4()] = {'Hour': str(k), 'Hits': str(v)} model.importDict(tableData) table.resizeColumn(0, 100) table.resizeColumn(1, 100) table.sortTable(columnName='Hour') table.redrawTable() else: RandomWebLogsWindow.deiconify()
class DataTable(ttk.Frame): def __init__(self, master,data=None,columns=None, upperColumnHeaders=None,**kw): ttk.Frame.__init__(self,master) self.tmodel = TableModel() if data!=None: self.tmodel.importDict(data,None,columns) self.table = self.create_table(self.tmodel,upperColumnHeaders,**kw) self.table.createTableFrame() return def set_data(self,data,columns): self.table.createfromDict(data,columns) self.table.createTableFrame() def create_table(self,tmodel,upperColumnHeaders,**kw): return TableCanvas(self, tmodel,upperColumnHeaders=upperColumnHeaders,**kw) def redraw(self): self.table.createTableFrame()
def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_pers"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_pers"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget()
def initTable(self): self.tabFm = Tkinter.Frame(self.top) self.tabFm.pack(expand=True, fill=Tkinter.BOTH) # 后期修改 self.top.geometry('920x700+200+100') self.model = TableModel(rows=0, columns=0) # like HTML self.table = TableCanvas(self.tabFm, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial', 12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS self.table.createTableFrame() self.colnames = ('ID', '姓名', '年龄', '加入时间') for name in self.colnames: self.table.addColumn(name) self.refresh()
def initTable(self, ev = None): self.tableFrame = Tkinter.Frame(self.top) self.tableFrame.pack(expand = True, fill = Tkinter.BOTH) # 后期修改 self.top.geometry('920x700+200+100') self.model = TableModel(rows = 0, columns = 0) # like HTML self.bookTable = TableCanvas(self.tableFrame, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial',12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS self.bookTable.createTableFrame() self.colnames = ('ISBN', '书名', '作者', '出版社', '出版时间', '价格') for name in self.colnames: self.bookTable.addColumn(name) self.bookTable.addRows(1) self.bookTable.autoResizeColumns()
def ratSightings(self): #call API for data r = requests.get( 'http://ec2-54-174-96-216.compute-1.amazonaws.com:9000/showRecords' ) rtext = r.text rawdata = json.loads(rtext) #create table & model self.ratSightingView = Toplevel() self.ratSightingView.title("List of recent rat sightings") self.rattable = Frame(self.ratSightingView) self.rattable.pack() model = TableModel() model.importDict(rawdata) #convert date column to datetime data type for x in range(len(rawdata)): datestr = model.getValueAt(x, 6) try: date = datetime.datetime.strptime(datestr, '%m/%d/%Y %I:%M:%S %p') model.setValueAt(date.strftime('%Y/%m/%d %I:%M:%S %p'), x, 6) except: try: dt = parser.parse(datestr) model.setValueAt(date.strftime('%Y/%m/%d %I:%M:%S %p'), x, 6) except: pass pass #get data into table table = TableCanvas(self.rattable, model=model) table.createTableFrame() #sort by date table.sortTable(columnName='date') '''
def initialize(self): mainframe = Frame(self,padx=3, pady=12) mainframe.grid(column=0, row=0, sticky=(N,E,W,S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.minsize(400, 400) subframe = Frame(mainframe) subframe.grid(row=0, column=0, sticky="NW") label = Label(subframe, text="Stock Symbol : ") label.pack(side="left") mainframe.symTextIn = Entry(subframe) self.sysmTextIn = mainframe.symTextIn self.sysmTextIn.bind("<Return>", self.addStock) mainframe.symTextIn.pack(side="left") addButton = Button(subframe,text=u"Add", command=self.addStock) addButton.pack(side="left", pady=5, padx=5) blueRow = Label(mainframe,fg="white",bg="blue") blueRow.grid(column=0,row=1,columnspan=3,sticky=(E,W)) mainframe.columnconfigure(0, weight=1) self.tableframe = Frame(mainframe, height=200, width=200, background="black") self.tableframe.grid(column=0, row=2,columnspan=3, sticky=(N,E,W,S)) mainframe.rowconfigure(2, weight=1) mainframe.columnconfigure(0, weight=1) mainframe.bind("<Return>", self.addStock) self.sysmTextIn.focus() #Create column Headers. self.model = TableModel(newdict=self.Objcolumn.getColumnsDict()) self.table = TableCanvas(self.tableframe, model=self.model, cols=len(self.Objcolumn.getColumns()),thefont=('Arial',9), rowheight=18, cellwidth=80, editable=False, selectedcolor='white', rowselectedcolor='white', autoresizecols=0, inset=0, width=350) self.model.importDict({'rec0' : {'Symbol' : ' ', 'Last Price':' ', 'Change':' ','%Change':' ' #,'Prev Close':' ','Bid':' ','Ask':' ' }}) self.table.createTableFrame() self.table.redrawTable()
def __table__(self, master): try: if self.rule_win.state() == 'normal': pass except: data = {} colnums = ['Rule', 'Node', 'Question', 'Yes', 'No'] rule_dict = self.df.ix[:, 'Rule':'No'] for r in range(len(rule_dict.index)): plice = {} for c in range(len(rule_dict.columns)): if rule_dict.iloc[r, c] == 'nan': plice[rule_dict.columns[c]] = ' ' else: plice[rule_dict.columns[c]] = rule_dict.iloc[r, c] data[str(r)] = plice self.rule_win = Toplevel(master) frame = Frame(self.rule_win) frame.pack() model = TableModel() for key in colnums: model.addColumn(key) #sort the columns model.importDict(data) table = TableCanvas(frame, model=model, width=800, height=500, rowheight=20, editable=False, cellbackgr='#E3F6CE', reverseorder=1, rowselectedcolor='yellow') table.createTableFrame() table.sortTable(columnName='Rule')
class GraficInterfaceDb: def __init__(self, parent): self.listEnfermedad = ['a', "d", "c"] self.listMedicamentos = ['a', "d", "c"] self.listObserver = [] self.actualizarListas() self.actualrow = 0 self.rowEvent = 99 #Ventana de tablas y entradas self.r1 = parent self.r = Frame(self.r1) self.r1.wm_title("Ventana de busqueda") self.group = LabelFrame(self.r, bd=0) # self.group.grid(row=0,column=0,sticky=NW, padx=5, pady=5) self.group.pack(side=LEFT) self.r.pack(expand=True, fill='x', side=LEFT) # Ventana que muestra antecedesntes y informacion especifica de radiografia self.a = Frame(self.r1, padx=20, pady=20) self.b = VentanaDetalles(self.a) self.b.setWindow(self) self.a.pack(side=RIGHT) #Filtrar por id self.putInPlace(IdSearch) #Filtrar por nombre self.putInPlace(NameSearch) #Filtrar por apellido self.putInPlace(LastNameSearch) #Filtrar por Rut self.putInPlace(RutSearch) #Filtrar por sexo self.putInPlace(SexoSearch) #Filtrar por Enfermedad y confirmado comboBox self.listObserver.append(self.putInPlace(Enfermedadearch)) #Filtro confirmado self.putInPlace(ConfirmadoSearch) #Tipo de radiografia self.putInPlace(TipoRadioSearch) #Fecha inicio fecha final self.putInPlace(FechaSearch) #Fuma self.putInPlace(FumaSearch) #Medicamento self.listObserver.append(self.putInPlace(MedicamentoSearch)) #Mostrar resultados marco11 = Frame(self.r) bSearch = Button(marco11, text="Busqueda", command=self.doQuery) bSearch.pack(padx=5, pady=5) lResultados = Label(marco11, text="Resultados de query: ") lResultados.pack(padx=5, pady=5) # marco11.grid(row=self.actualrow, column=0,sticky=W, padx=5, pady=5) marco11.pack() self.actualrow += 1 marco12 = Frame(self.r) self.model = TableModel() self.table = TableCanvas(marco12, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial', 9), rowheight=18, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) self.table.createTableFrame() # marco12.grid(row=self.actualrow,column=0,sticky=W, padx=5, pady=5) marco12.pack(expand=False, fill='x') self.actualrow += 1 self.actualizarListas() self.r1.bind("<Button-1>", self.changeCurrentId) def getEnfList(self): print "Lista de enfermedad " + str(self.listEnfermedad) return self.listEnfermedad def getMedList(self): return self.listMedicamentos #Si quieres gridear creo que aqui es un buen lugar def putInPlace(self, claseBusqueda): #SI ACA COLOCAS TRUE TODOS LOS COMPONENTES NO HACEN PACK Y SE GUARDAN EN LISTA self.listaComponente #Puedes cambiar tanto el parent como el grid objetoNuevo = claseBusqueda(self.group, True) cont = 1 #Ejemplo de como se podrian sacar los componentes for comp in objetoNuevo.listaComponente: comp.grid(row=self.actualrow, column=cont) # comp.pack() cont += 1 listaSearch.append(objetoNuevo) self.actualrow += 1 return objetoNuevo def getCurrentIdRadio(self): try: print self.table.get_currentRecord() return self.table.get_currentRecord()[idColumnName] except: return None def actualizarListas(self): self.listEnfermedad = auxProcessList(queryListaEnf, "") self.listMedicamentos = auxProcessList(queryListaMed, "") for element in self.listObserver: element.update(self) def changeCurrentId(self, event): print "Antiguo ", self.rowEvent, " real ", self.table.currentrow if (self.rowEvent != self.table.currentrow): self.rowEvent = self.table.currentrow print("Evento activado") self.b.setValues(event) pass def doQuery(self): self.actualizarListas() print "Im about to query" resultSearch = [] for element in listaSearch: if (element.isActive()): result = element.giveFilterResults() print result if (len(resultSearch) != 0): set1 = set(result) set2 = set(resultSearch) set3 = set1 & set2 print set3 resultSearch = set3 else: resultSearch = result self.showResultInTable(resultSearch) return def showResultInTable(self, lista): data = {} resultQuery = [] #Ahora esta mostrando todas las radiografias que encuentra con criterios (incluso si no tieneen enf asociada) contador = 0 columnNames = {} if (len(lista) != 0): resultQuery = askDb(queryMostrar, (tuple(lista), )) resultQuery2 = askDb(metaquery, (tuple(lista), )) for index, name in enumerate(resultQuery2): columnNames[index] = name[0] for element in resultQuery: temp = zip(element, range(len(element))) tempDic = {} for atomicVal in temp: print atomicVal tempDic[str(columnNames[atomicVal[1]])] = str(atomicVal[0]) data[str(contador)] = tempDic contador += 1 self.model.setupModel({}) self.model.importDict(data) self.table.redrawTable() self.b.setValues(0) return
import time import Tkinter from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel master = Tkinter.Tk() tframe = Tkinter.Frame(master) tframe.pack() table = TableCanvas(tframe) table.createTableFrame() # Create a model from data and init. model = TableModel() table = TableCanvas(tframe, model=model,width=1200, height=800) table.createTableFrame() raw_input('Redraw table and put data into it!') # Call to update after content change. table.redrawTable() #To import from a dictionary we get a handle on the model #(or we can create the model first and supply it as an argument to the table constructor): data = {'rec1': {'col1': 99.88, 'col2': 108.79, 'label': 'rec1'}, 'rec2': {'col1': 99.88, 'col2': 108.79, 'label': 'rec2'}, 'rec3': {'col1':1.0, 'label':'rec3'}, 'rec4': {'col1':2.0, 'label':'rec4'} } model = table.model model.importDict(data) #can import from a dictionary to populate model
from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel from Tkinter import * master = Tk() tframe = Frame(master) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) #model = table.model #model.addColumn('col1') #model.addColumn('col2') #model.addColumn() data = { '1' : {'col1': 99.88, 'col2': 108.79 }, '2' : {'col1': 99.88, 'col2': 108.79}} model.importDict(data) table.createTableFrame() #table.pack() master.mainloop()
def set_columns(self, columns, main_column=None): self.deleteColumns() for col in columns: TableModel.addColumn(self, col) self.main_column = columns[0] if main_column is None else main_column
def __init__(self, frame, usable_width, direction): self.deleted = False self.directed = direction self.ftable = Frame(frame.ftables) self.ft = Frame(self.ftable) self.fnp = Frame(self.ftable) #frame network properties if(usable_width > 1500) : button_width=17 button_width_plot=7 font=('Verdana',9) image_button = 23 list_fonts = list( tkFont.families() ) elif(usable_width > 1200): button_width=15 button_width_plot=6 image_button = 28 font=('Verdana',10) else: button_width=14 button_width_plot=5 image_button = 28 font=('Verdana',8) if(usable_width > 1500): self.save_img = PhotoImage(file="save.gif") self.load_img = PhotoImage(file="load.gif") self.delete_img = PhotoImage(file="delete.gif") elif(usable_width > 1200): self.save_img = PhotoImage(file="save22.gif") self.load_img = PhotoImage(file="load22.gif") self.delete_img = PhotoImage(file="delete.gif") else: self.save_img = PhotoImage(file="save20.gif") self.load_img = PhotoImage(file="load20.gif") self.delete_img = PhotoImage(file="delete.gif") labelfnp_width = 10 pos = 0 # buttons area for the right panel of each graph self.buttonSave = Button(master=self.fnp, image=self.save_img, command=lambda num=frame.number_table: save_network(frame, num), relief=FLAT, width=image_button) self.buttonSave.image = self.save_img self.buttonSave.grid(row=0, column=0, pady=1, padx=1) self.buttonDelete = Button(master=self.fnp, image=self.delete_img, command=lambda num=frame.number_table: delete_network(frame, num), relief=FLAT, width=image_button) self.buttonDelete.image = self.delete_img self.buttonDelete.grid(row=pos, column=1, pady=1, padx=1) pos += 1 self.plot_button = Button(master=self.fnp, text='Plot', command=lambda num=frame.number_table: plot_graph(frame, num), width=button_width) self.plot_button.grid(row=pos, column=0, columnspan=2, pady=2, padx=5) pos += 1 self.netPro_label = Label(self.fnp, text="Network properties:", width=3*labelfnp_width, anchor=CENTER) self.netPro_label.grid(row=pos, column=0, columnspan=2, pady=2, padx=5) pos += 1 self.number_nodesLabel = Label(self.fnp, text="Nodes: ", width=labelfnp_width, anchor=W) self.number_nodesLabel.grid(row=pos, column=0, pady=2, padx=5) self.number_nodes_str = StringVar() self.number_nodes_l = Label(self.fnp, textvariable=self.number_nodes_str, width=labelfnp_width, anchor=W) self.number_nodes_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.number_arcsLabel = Label(self.fnp, text="Arcs: ", width=labelfnp_width, anchor=W) self.number_arcsLabel.grid(row=pos, column=0, pady=2, padx=5) self.number_arcs_str = StringVar() self.number_arcs_l = Label(self.fnp, textvariable=self.number_arcs_str, width=labelfnp_width, anchor=W) self.number_arcs_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.number_diameterLabel = Label(self.fnp, text="Diameter: ", width=labelfnp_width, anchor=W) self.number_diameterLabel.grid(row=pos, column=0, pady=2, padx=5) self.diameter_str = StringVar() self.diameter_l = Label(self.fnp, textvariable=self.diameter_str, width=labelfnp_width, anchor=W) self.diameter_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.assortativityLabel = Label(self.fnp, text="Assortativity: ", width=labelfnp_width, anchor=W) self.assortativityLabel.grid(row=pos, column=0, pady=2, padx=5) self.assortativity_str = StringVar() self.assortativity_l = Label(self.fnp, textvariable=self.assortativity_str, width=labelfnp_width, anchor=W) self.assortativity_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.entropyLabel = Label(self.fnp, text="Entropy: ", width=labelfnp_width, anchor=W) self.entropyLabel.grid(row=pos, column=0, pady=2, padx=5) self.entropy_str = StringVar() self.entropy_l = Label(self.fnp, textvariable=self.entropy_str, width=labelfnp_width, anchor=W) self.entropy_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.subgraph_ind_sub = Button(master=self.fnp, text='Induced subgraph', font=font, command=lambda num=frame.number_table: induced_subgraph(frame, num, usable_width), width=button_width) self.subgraph_ind_sub.grid(row=pos, column=0, pady=2, padx=5) pos+=1 self.subgraph_ind_sub_lev = Button(master=self.fnp, text='Subgraph level', font=font, command=lambda num=frame.number_table: subgraph_levels(frame, num, usable_width), width=button_width) self.subgraph_ind_sub_lev.grid(row=pos, column=0, pady=2, padx=5) self.frame_but = Frame(self.fnp) #table part, create and fill columns self.columnNames = columnNames self.model = TableModel() self.model.data = {} for i in xrange(len(self.columnNames)): if(direction): if(columnNames[i] != "Information centrality"): self.model.addColumn(self.columnNames[i]) else: if(columnNames[i] != 'Eccentricity in'): if(columnNames[i] != 'Vibrational centrality in'): if(columnNames[i] != 'In degree'): if(columnNames[i] != 'Total degree'): self.model.addColumn(self.columnNames[i].replace(" out", "").replace("Out degree", "Degree")) if(usable_width > 1500): thefont=30 rowheight=22 else: thefont=5 rowheight=20 self.table = TableCanvas(self.ft, model=self.model, rows=0, cols=0, rowheaderwidth=0, rowheight=rowheight, cellbackgr='#ffffff', thefont=thefont, editable=False, showkeynamesinheader=True, autoresizecols=True, fill=X) self.model.addRow() self.table.createTableFrame() self.file_name = StringVar() self.file_name_label = Label(self.ftable, textvariable=self.file_name) self.file_name_label.pack(side=TOP) self.ft.pack(side=LEFT, expand=True, fill=X) self.fnp.pack(side=RIGHT) self.ftable.pack(expand=True, fill=X) #create the centrality list self.centrality = [[] for x in xrange(len(self.columnNames))] self.table.fontsize=thefont self.table.setFontSize() self.adj_matrix = None self.laplacian_psinv = None frame.canvas.config(scrollregion=frame.canvas.bbox("all"))
def __init__(self, parent, top, opt): ''' Constructor ''' self.__parent = parent self.__top = top self.__opt = opt config = ConfigManager.ConfigManager.getInstance() # Period to delay between table refreshes self.__update_period = config.get('performance', 'telem_table_update_period') # # Status updater singleton # self.__status_update = status_updater.StatusUpdater.getInstance() # # Instance the channel loader here and get all channel names # self.__channel_loader = channel_loader.ChannelLoader.getInstance() self.__channel_names_list = self.__channel_loader.getNameDict().values( ) self.__channel_names_dict = self.__channel_loader.getNameDict() num_channels = len(self.__channel_loader.getNameDict()) # # Container Frame f = Tkinter.Frame(parent) f.pack(side=Tkinter.TOP, anchor=Tkinter.N, fill=Tkinter.BOTH, expand=1) # # Create a model and connect it to a table on a canvas # self.__model = TableModel() self.__table = TableCanvas(f, model=self.__model, width=1200, height=800) # Set font font = config.get('tables', 'font') font_size = config.get('tables', 'font_size') self.__table.thefont = (font, font_size) self.__table.rowheight = int(font_size) + 5 self.__table.createTableFrame() self.__table.redrawTable() # Mouse movement causes flyover text. This is not needed. # Unbind the appropriate event handler self.__table.unbind('<Motion>') # # Init. the table with a standard set of column headers # data = {'1': {'Channel': None}} self.__model.importDict( data) # can import from a dictionary to populate model self.__table.addColumn('Id') self.__table.addColumn('Time') self.__table.addColumn('Value') for i in range(2, num_channels + 1): self.__table.addRow("%s" % i) self.__table.align = 'w' self.__table.redrawTable() self.__table.maxcellwidth = 500 # Remove Row and cell highlight color self.__table.rowselectedcolor = None self.__table.selectedcolor = None # Rebind <B1-Motion> event to catch exception from column resize error self.__table.tablecolheader.unbind('<B1-Motion') self.__table.tablecolheader.bind('<B1-Motion>', self.__handle_column_motion) self.__table.tablecolheader.unbind('<ButtonRelease-1>') self.__table.tablecolheader.bind('<ButtonRelease-1>', self.__handle_column_release) # Make table read only self.__table.editable = False # # Pop-up Channel Telemetry Filter Selection and Active Filter Status. # f2 = Tkinter.LabelFrame(f, text="Channel Telemetry Filtering:", padx=5, pady=5) f2.grid(row=2, column=0, columnspan=4, sticky=Tkinter.W + Tkinter.E) # b1 = Tkinter.Button(f2, text="Select Channels", command=self.__select) b1.pack(side=Tkinter.LEFT) # Hex value toggle self.__print_hex = Tkinter.IntVar() self.__print_hex.set(0) self.__hex_cb = Tkinter.Checkbutton(f2, text="Show Hex", variable=self.__print_hex, pady=5) self.__hex_cb.pack(side=Tkinter.RIGHT) # self.__e1 = Pmw.ScrolledField(f2, labelpos=Tkinter.W, labelmargin=0, text="None") self.__e1.pack(side=Tkinter.LEFT, expand=1, fill=Tkinter.X) self.__e1.component('entry').config(width=60) self.__e1.component('label').config(text='Active Filter Selected:') # # This is a channel id key to row value dictionary # built up over runtime to update table. # self.__row_dict = dict() self.__row_max = 1 # # List of active channels to display self.__channel_names_list.sort() self.__channels_active_list = self.__channel_names_list self.__inactive_channels = []
from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel from Tkinter import * master = Tk() tframe = Frame(master) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) #model = table.model #model.addColumn('col1') #model.addColumn('col2') #model.addColumn() data = { '1': { 'col1': 99.88, 'col2': 108.79 }, '2': { 'col1': 99.88, 'col2': 108.79 } } model.importDict(data) table.createTableFrame() #table.pack() master.mainloop()
def __init__(self, **kwargs): TableModel.__init__(self, **kwargs) self.main_column = ''
class Watchlist(Tk): def __init__(self,parent): Tk.__init__(self,parent) self.parent = parent self.currentRow = 1 self.rows = [] self.Objcolumn = Columns() self.initialize() def addStock(self, args=None): stockSym = self.sysmTextIn.get() if stockSym == None: return else : self.addRow(stockSym) return def addRow(self, stockSym): self.sysmTextIn.delete(0, END) searchterms = [('Symbol', stockSym.upper(), '=', 'AND')] symbolCol = self.model.getColumnData(columnIndex=self.model.getColumnIndex(columnName="Symbol"), columnName="Symbol", filters=searchterms) if stockSym.upper() in symbolCol: return result = ystockquote.get_all(stockSym.upper()) row = Rows(result, stockSym.upper()) dictrow = row.getRow() colIndex = self.model.getColumnIndex(columnName="Symbol") stockSym = self.model.getValueAt(rowIndex=0, columnIndex=colIndex) if stockSym == " ": row0 = self.table.getSelectedRow() self.model.deleteRow(row0) self.table.setSelectedRow(row0-1) self.table.clearSelected() else: self.currentRow = self.currentRow + 1 self.model.importDict({ "%s%d" % ("rec", self.currentRow) : dictrow}) change = float(dictrow['Change']) if change > 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="Change"),color="green", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="green", key="fg") if change < 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="Change"),color="red", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="red", key="fg") self.table.redrawTable() self.after(5000, self.updateTableValue, "%s%d" % ("rec", self.currentRow)) def fadeIn(self, rec) : if rec not in self.model.data: return self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Last Price"),color="white") self.table.redrawTable() def updateTableValue(self, rec): increased = False decreased = False if rec not in self.model.data: return result = ystockquote.get_all(self.model.data[rec]['Symbol'].upper()) row = Rows(result, self.model.data[rec]['Symbol'].upper()) dictrow = row.getRow() change = float(dictrow['Change']) #print "update table value" + self.model.data[rec]['Symbol'].upper() if change > 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Change"),color="green", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="green", key="fg") if change < 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Change"),color="red", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="red", key="fg") if float(self.model.data[rec]['Last Price']) > float(dictrow['Last Price']): color="Red" decreased = True if float(self.model.data[rec]['Last Price']) < float(dictrow['Last Price']): color="Green" increased = True if (decreased == True) or (increased == True): self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Last Price"),color=color) for col in self.model.data[rec]: self.model.data[rec][col] = dictrow[col] self.table.redrawTable() self.id = self.after(5000, self.updateTableValue, rec) self.id = self.after(1000, self.fadeIn, rec) def initialize(self): mainframe = Frame(self,padx=3, pady=12) mainframe.grid(column=0, row=0, sticky=(N,E,W,S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.minsize(400, 400) subframe = Frame(mainframe) subframe.grid(row=0, column=0, sticky="NW") label = Label(subframe, text="Stock Symbol : ") label.pack(side="left") mainframe.symTextIn = Entry(subframe) self.sysmTextIn = mainframe.symTextIn self.sysmTextIn.bind("<Return>", self.addStock) mainframe.symTextIn.pack(side="left") addButton = Button(subframe,text=u"Add", command=self.addStock) addButton.pack(side="left", pady=5, padx=5) blueRow = Label(mainframe,fg="white",bg="blue") blueRow.grid(column=0,row=1,columnspan=3,sticky=(E,W)) mainframe.columnconfigure(0, weight=1) self.tableframe = Frame(mainframe, height=200, width=200, background="black") self.tableframe.grid(column=0, row=2,columnspan=3, sticky=(N,E,W,S)) mainframe.rowconfigure(2, weight=1) mainframe.columnconfigure(0, weight=1) mainframe.bind("<Return>", self.addStock) self.sysmTextIn.focus() #Create column Headers. self.model = TableModel(newdict=self.Objcolumn.getColumnsDict()) self.table = TableCanvas(self.tableframe, model=self.model, cols=len(self.Objcolumn.getColumns()),thefont=('Arial',9), rowheight=18, cellwidth=80, editable=False, selectedcolor='white', rowselectedcolor='white', autoresizecols=0, inset=0, width=350) self.model.importDict({'rec0' : {'Symbol' : ' ', 'Last Price':' ', 'Change':' ','%Change':' ' #,'Prev Close':' ','Bid':' ','Ask':' ' }}) self.table.createTableFrame() self.table.redrawTable()
def __init__(self, parent): self.listEnfermedad = ['a', "d", "c"] self.listMedicamentos = ['a', "d", "c"] self.listObserver = [] self.actualizarListas() self.actualrow = 0 self.rowEvent = 99 #Ventana de tablas y entradas self.r1 = parent self.r = Frame(self.r1) self.r1.wm_title("Ventana de busqueda") self.group = LabelFrame(self.r, bd=0) # self.group.grid(row=0,column=0,sticky=NW, padx=5, pady=5) self.group.pack(side=LEFT) self.r.pack(expand=True, fill='x', side=LEFT) # Ventana que muestra antecedesntes y informacion especifica de radiografia self.a = Frame(self.r1, padx=20, pady=20) self.b = VentanaDetalles(self.a) self.b.setWindow(self) self.a.pack(side=RIGHT) #Filtrar por id self.putInPlace(IdSearch) #Filtrar por nombre self.putInPlace(NameSearch) #Filtrar por apellido self.putInPlace(LastNameSearch) #Filtrar por Rut self.putInPlace(RutSearch) #Filtrar por sexo self.putInPlace(SexoSearch) #Filtrar por Enfermedad y confirmado comboBox self.listObserver.append(self.putInPlace(Enfermedadearch)) #Filtro confirmado self.putInPlace(ConfirmadoSearch) #Tipo de radiografia self.putInPlace(TipoRadioSearch) #Fecha inicio fecha final self.putInPlace(FechaSearch) #Fuma self.putInPlace(FumaSearch) #Medicamento self.listObserver.append(self.putInPlace(MedicamentoSearch)) #Mostrar resultados marco11 = Frame(self.r) bSearch = Button(marco11, text="Busqueda", command=self.doQuery) bSearch.pack(padx=5, pady=5) lResultados = Label(marco11, text="Resultados de query: ") lResultados.pack(padx=5, pady=5) # marco11.grid(row=self.actualrow, column=0,sticky=W, padx=5, pady=5) marco11.pack() self.actualrow += 1 marco12 = Frame(self.r) self.model = TableModel() self.table = TableCanvas(marco12, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial', 9), rowheight=18, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) self.table.createTableFrame() # marco12.grid(row=self.actualrow,column=0,sticky=W, padx=5, pady=5) marco12.pack(expand=False, fill='x') self.actualrow += 1 self.actualizarListas() self.r1.bind("<Button-1>", self.changeCurrentId)
def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [ row_name[i] + it for i, it in enumerate(statistic.get_common_stat()) ]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget()
def __init__(self,parent): self.listEnfermedad = ['a',"d","c"] self.listMedicamentos = ['a',"d","c"] self.listObserver = [] self.actualizarListas() self.actualrow = 0 self.rowEvent = 99 #Ventana de tablas y entradas self.r1 = parent self.r = Frame(self.r1) self.r1.wm_title("Ventana de busqueda") self.group = LabelFrame(self.r,bd=0) # self.group.grid(row=0,column=0,sticky=NW, padx=5, pady=5) self.group.pack(side=LEFT) self.r.pack(expand=True, fill='x',side=LEFT) # Ventana que muestra antecedesntes y informacion especifica de radiografia self.a = Frame(self.r1,padx=20, pady=20) self.b = VentanaDetalles(self.a) self.b.setWindow(self) self.a.pack(side=RIGHT) #Filtrar por id self.putInPlace(IdSearch) #Filtrar por nombre self.putInPlace(NameSearch) #Filtrar por apellido self.putInPlace(LastNameSearch) #Filtrar por Rut self.putInPlace(RutSearch) #Filtrar por sexo self.putInPlace(SexoSearch) #Filtrar por Enfermedad y confirmado comboBox self.listObserver.append(self.putInPlace(Enfermedadearch)) #Filtro confirmado self.putInPlace(ConfirmadoSearch) #Tipo de radiografia self.putInPlace(TipoRadioSearch) #Fecha inicio fecha final self.putInPlace(FechaSearch) #Fuma self.putInPlace(FumaSearch) #Medicamento self.listObserver.append(self.putInPlace(MedicamentoSearch)) #Mostrar resultados marco11 = Frame(self.r) bSearch = Button(marco11, text="Busqueda", command=self.doQuery) bSearch.pack(padx=5, pady=5) lResultados = Label(marco11, text="Resultados de query: ") lResultados.pack(padx=5, pady=5) # marco11.grid(row=self.actualrow, column=0,sticky=W, padx=5, pady=5) marco11.pack() self.actualrow+=1 marco12 = Frame(self.r) self.model = TableModel() self.table = TableCanvas(marco12, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial',9),rowheight=18, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) self.table.createTableFrame() # marco12.grid(row=self.actualrow,column=0,sticky=W, padx=5, pady=5) marco12.pack(expand=False, fill='x') self.actualrow += 1 self.actualizarListas() self.r1.bind("<Button-1>",self.changeCurrentId)
from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel from Tkinter import * master = Tk() tframe = Frame(master) tframe.pack() model = TableModel() model.addColumn('c1') model.addColumn('c2') model.addRow('1') model.addRow('2') row = 1 column = 1 table = TableCanvas(tframe, model=model) table.model.data['1']['c1'] = 10 table.createTableFrame() #table.pack() master.mainloop()
class _StatisticDialog(TopDialog): def __init__(self, parent, factory, statistic, stat_count_row): TopDialog.__init__(self, parent, (statistic, stat_count_row)) self.factory = factory self.title(_("win_statistic_title")) self.wait_visibility() self.set_size(self.table_detailed_stat.get_totalWidth(), 750) self.resizable(True, True) self.grab_set() self.run() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [ row_name[i] + it for i, it in enumerate(statistic.get_common_stat()) ]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas( self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column( col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append( Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def init_window(self, (statistic, stat_count_row)): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en()
root.geometry('1000x700') f = Figure(figsize=(4, 4), dpi=50) axis = f.add_subplot(111) canvas = FigureCanvasTkAgg(f, master=root) canvas.get_tk_widget().place(x=10, y=30) frame2 = Frame(root) frame2.place(x=20, y=300) X_Axis = pylab.arange(0, 100, 1) plotFigure = Figure(figsize=(4, 4), dpi=50) axis2 = plotFigure.add_subplot(111) axis2.grid(True) axis2.set_title("Mean value per Frame") axis2.axis([0, 100, 0, 255]) Plot = axis2.plot(X_Axis, [0] * 100, 'o-', color='r', markersize=6) model = TableModel() table = TableCanvas(frame2, model, height=100, width=300) model = table.model table.createTableFrame() canvas2 = FigureCanvasTkAgg(plotFigure, master=root) canvas2.get_tk_widget().place(x=500, y=30) b1 = Button(root, text="Start", bg='white', command=video_start).place(x=50, y=600) b2 = Button(root, text="Stop", bg='white', command=video_stop).place(x=400, y=600) root.mainloop() #===========================================================================================
def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas( self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column( col).width = self.model_ru_en.get_column(col).width
from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel from Tkinter import * master = Tk() tframe = Frame(master) tframe.pack() model = TableModel() model.addColumn('c1') model.addColumn('c2') model.addRow('1') model.addRow('2') row= 1 column = 1 table = TableCanvas(tframe,model=model) table.model.data['1']['c1']= 10 table.createTableFrame() #table.pack() master.mainloop()
class ManagerUI(object): def __init__(self, top, conn): self.top = top self.conn = conn self.initComponent() self.initTable() self.quitButton = Tkinter.Button(self.top, text='退出', command=self.top.quit) self.quitButton.pack() def initComponent(self): entryWidth = 40 self.nameFm = Tkinter.Frame(self.top) self.name = Tkinter.StringVar(self.nameFm) self.nameLabel = Tkinter.Label(self.nameFm, text='姓名:') self.nameLabel.pack(side=Tkinter.LEFT) self.nameEntry = Tkinter.Entry(self.nameFm, width=entryWidth, textvariable=self.name) self.nameEntry.bind('<Return>', self.get) self.nameEntry.pack(side=Tkinter.LEFT) self.nameFm.pack() self.ageFm = Tkinter.Frame(self.top) self.age = Tkinter.StringVar(self.ageFm) self.ageLabel = Tkinter.Label(self.ageFm, text='年龄:') self.ageLabel.pack(side=Tkinter.LEFT) self.ageEntry = Tkinter.Entry(self.ageFm, width=entryWidth, textvariable=self.age) self.ageEntry.bind('<Return>', self.get) self.ageEntry.pack(side=Tkinter.LEFT) self.ageFm.pack() self.jointimeFm = Tkinter.Frame(self.top) self.jointime = Tkinter.StringVar(self.jointimeFm) self.jointimeLabel = Tkinter.Label(self.jointimeFm, text='加入时间:') self.jointimeLabel.pack(side=Tkinter.LEFT) self.jointimeEntry = Tkinter.Entry(self.jointimeFm, width=entryWidth, textvariable=self.jointime) self.jointimeEntry.bind('<Return>', self.get) self.jointimeEntry.pack(side=Tkinter.LEFT) self.jointimeFm.pack() self.btnfm = Tkinter.Frame(self.top) self.refreshButton = Tkinter.Button(self.btnfm, text='刷新', command=self.refresh) self.addButton = Tkinter.Button(self.btnfm, text='添加', command=self.add) self.getButton = Tkinter.Button(self.btnfm, text='查询', command=self.get) self.deleteButton = Tkinter.Button(self.btnfm, text='删除', command=self.delete) self.resetButton = Tkinter.Button(self.btnfm, text='重置', command=self.reset) self.refreshButton.pack(side=Tkinter.LEFT) self.addButton.pack(side=Tkinter.LEFT) self.getButton.pack(side=Tkinter.LEFT) self.deleteButton.pack(side=Tkinter.LEFT) self.resetButton.pack(side=Tkinter.LEFT) self.btnfm.pack() def initTable(self): self.tabFm = Tkinter.Frame(self.top) self.tabFm.pack(expand=True, fill=Tkinter.BOTH) # 后期修改 self.top.geometry('920x700+200+100') self.model = TableModel(rows=0, columns=0) # like HTML self.table = TableCanvas(self.tabFm, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial', 12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS self.table.createTableFrame() self.colnames = ('ID', '姓名', '年龄', '加入时间') for name in self.colnames: self.table.addColumn(name) self.refresh() def refresh(self, ev=None): try: rs = self.conn.execute('select * from person') rs = rs.fetchall() self.model.deleteRows() self.table.addRows(len(rs)) self.table.redrawTable() for index, row in enumerate(rs): for i in range(len(self.colnames)): if type(row[i]) == unicode: self.model.data[index][self.colnames[i]] = ( '' + row[i]).encode('utf8') elif type(row[i]) == datetime.date: self.model.data[index][ self.colnames[i]] = row[i].strftime('%Y-%m-%d') else: # long or float self.model.data[index][self.colnames[i]] = str(row[i]) self.table.autoResizeColumns() except Exception as e: tkMessageBox.showinfo('提示', '刷新失败:%s' % e) def add(self, ev=None): try: self.conn.execute( 'INSERT INTO person(NAME, AGE, JOINTIME) values("%s", %s, "%s")' % (self.name.get().encode('utf8'), self.age.get(), self.jointime.get())) self.conn.commit() self.refresh() except Exception as e: tkMessageBox.showinfo('提示', '添加失败:%s' % e) def get(self, ev=None): try: sql = 'select * from person where 1=1' if self.name.get(): sql = sql + ' AND name like "%%%s%%"' % self.name.get() if self.age.get(): sql = sql + ' AND age = %s' % self.age.get() rs = self.conn.execute(sql) rs = rs.fetchall() self.model.deleteRows() self.table.addRows(len(rs)) self.table.redrawTable() for index, row in enumerate(rs): for i in range(len(self.colnames)): if type(row[i]) == unicode: self.model.data[index][self.colnames[i]] = ( '' + row[i]).encode('utf8') elif type(row[i]) == datetime.date: self.model.data[index][ self.colnames[i]] = row[i].strftime('%Y-%m-%d') else: # long or float self.model.data[index][self.colnames[i]] = str(row[i]) self.table.autoResizeColumns() except Exception as e: tkMessageBox.showinfo('提示', '查询失败:%s' % e) def delete(self, ev=None): try: self.get() sql = 'DELETE FROM person where 1=1' if self.name.get(): sql = sql + ' AND name like "%%%s%%"' % self.name.get() if self.age.get(): sql = sql + ' AND age = %s' % self.age.get() if tkMessageBox.askyesnocancel('提示', '确认删除表中的记录?'): self.conn.execute(sql) self.conn.commit() self.refresh() except Exception as e: tkMessageBox.showinfo('提示', '删除失败:%s' % e) def reset(self, ev=None): self.name.set('') self.age.set('') self.jointime.set('')
def findTweetSentiment(self): """ Method for calculating the sentiment of each tweet. """ if not os.path.isfile(self.TwitterKeysFile): tkMessageBox.showerror("ERROR", "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.", parent = self.parent) return self.count += 1 if self.tweetSentimentOpenedFlag == False: # set window opened self.tweetSentimentOpenedFlag = True # initialize window global TweetSentimentWindow def toggleFlag(): self.tweetSentimentOpenedFlag = False TweetSentimentWindow.destroy() TweetSentimentWindow = tk.Toplevel(self) TweetSentimentWindow.minsize(600, 500) #TwitterKeysWindow.overrideredirect(True) TweetSentimentWindow.geometry("1000x500+100+100") TweetSentimentWindow.title("Tweet Sentiments (Zero values omitted)") TweetSentimentWindow.config(bd=5) TweetSentimentWindow.protocol("WM_DELETE_WINDOW", toggleFlag) # create a new TableModel for table data model = TableModel() # create a new TableCanvas for showing the table table = TableCanvas(TweetSentimentWindow, model=model, editable=False) table.createTableFrame() # dictionary for storing table data tableData = {} # calculate sentiments afinnfile = open(self.AFINNFile) scores = {} for line in afinnfile: term, score = line.split("\t") scores[term] = int(score) #print scores.items() positive = 0.0 negative = 0.0 outfile = open(self.TwitterStreamFile) for line in outfile: json_obj = json.loads(line) sentiment = 0 try: text = json_obj['text'].decode('utf-8') # clean the text text = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)","",text).split()) text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE) text = re.sub(r'RT', '', text, flags=re.MULTILINE) #print text text_list = text.split(' ') for char in text_list: if char in scores: sentiment += scores[char] if sentiment != 0: # add items to table data dictionary tableData[uuid.uuid4()] = {'Tweet': text, 'Score': str(sentiment)} if sentiment > 0: positive += 1 elif sentiment < 0: negative += 1 #print text + " " + str(sentiment) + "\n\n" except: #print "passed" pass # calculate ratio if positive > 0 and negative > 0: ratio = round(float(positive) / float(negative), 2) # insert and sort data in the table model.importDict(tableData) table.resizeColumn(0, 850) table.resizeColumn(1, 50) table.sortTable(columnName='Score') table.redrawTable() if positive > negative: extra = "The overall sentiment is POSITIVE." else: extra = "The overall sentiment is NEGATIVE." # show info box about the overall result tkMessageBox.showinfo("Score Ratio", "The ratio of positive vs. negative tweets is " + str(ratio) + ". " + extra, parent = TweetSentimentWindow)
def __init__(self, newdict=None, rows=None, columns=None): TableModel.__init__(self,newdict,rows,columns) self.use_regexp_filter = BooleanVar()
class GraficInterfaceDb: def __init__(self,parent): self.listEnfermedad = ['a',"d","c"] self.listMedicamentos = ['a',"d","c"] self.listObserver = [] self.actualizarListas() self.actualrow = 0 self.rowEvent = 99 #Ventana de tablas y entradas self.r1 = parent self.r = Frame(self.r1) self.r1.wm_title("Ventana de busqueda") self.group = LabelFrame(self.r,bd=0) # self.group.grid(row=0,column=0,sticky=NW, padx=5, pady=5) self.group.pack(side=LEFT) self.r.pack(expand=True, fill='x',side=LEFT) # Ventana que muestra antecedesntes y informacion especifica de radiografia self.a = Frame(self.r1,padx=20, pady=20) self.b = VentanaDetalles(self.a) self.b.setWindow(self) self.a.pack(side=RIGHT) #Filtrar por id self.putInPlace(IdSearch) #Filtrar por nombre self.putInPlace(NameSearch) #Filtrar por apellido self.putInPlace(LastNameSearch) #Filtrar por Rut self.putInPlace(RutSearch) #Filtrar por sexo self.putInPlace(SexoSearch) #Filtrar por Enfermedad y confirmado comboBox self.listObserver.append(self.putInPlace(Enfermedadearch)) #Filtro confirmado self.putInPlace(ConfirmadoSearch) #Tipo de radiografia self.putInPlace(TipoRadioSearch) #Fecha inicio fecha final self.putInPlace(FechaSearch) #Fuma self.putInPlace(FumaSearch) #Medicamento self.listObserver.append(self.putInPlace(MedicamentoSearch)) #Mostrar resultados marco11 = Frame(self.r) bSearch = Button(marco11, text="Busqueda", command=self.doQuery) bSearch.pack(padx=5, pady=5) lResultados = Label(marco11, text="Resultados de query: ") lResultados.pack(padx=5, pady=5) # marco11.grid(row=self.actualrow, column=0,sticky=W, padx=5, pady=5) marco11.pack() self.actualrow+=1 marco12 = Frame(self.r) self.model = TableModel() self.table = TableCanvas(marco12, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial',9),rowheight=18, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) self.table.createTableFrame() # marco12.grid(row=self.actualrow,column=0,sticky=W, padx=5, pady=5) marco12.pack(expand=False, fill='x') self.actualrow += 1 self.actualizarListas() self.r1.bind("<Button-1>",self.changeCurrentId) def getEnfList(self): print "Lista de enfermedad "+str(self.listEnfermedad) return self.listEnfermedad def getMedList(self): return self.listMedicamentos #Si quieres gridear creo que aqui es un buen lugar def putInPlace(self, claseBusqueda): #SI ACA COLOCAS TRUE TODOS LOS COMPONENTES NO HACEN PACK Y SE GUARDAN EN LISTA self.listaComponente #Puedes cambiar tanto el parent como el grid objetoNuevo = claseBusqueda(self.group,True) cont = 1 #Ejemplo de como se podrian sacar los componentes for comp in objetoNuevo.listaComponente: comp.grid(row=self.actualrow,column=cont) # comp.pack() cont+=1 listaSearch.append(objetoNuevo) self.actualrow+=1 return objetoNuevo def getCurrentIdRadio(self): try: print self.table.get_currentRecord() return self.table.get_currentRecord()[idColumnName] except: return None def actualizarListas(self): self.listEnfermedad = auxProcessList(queryListaEnf,"") self.listMedicamentos = auxProcessList(queryListaMed,"") for element in self.listObserver: element.update(self) def changeCurrentId(self,event): print "Antiguo ",self.rowEvent," real ",self.table.currentrow if (self.rowEvent != self.table.currentrow): self.rowEvent = self.table.currentrow print("Evento activado") self.b.setValues(event) pass def doQuery(self): self.actualizarListas() print "Im about to query" resultSearch = [] for element in listaSearch: if(element.isActive()): result = element.giveFilterResults() print result if (len(resultSearch) != 0): set1 = set(result) set2 = set(resultSearch) set3 = set1 & set2 print set3 resultSearch = set3 else: resultSearch = result self.showResultInTable(resultSearch) return def showResultInTable(self,lista): data = {} resultQuery = [] #Ahora esta mostrando todas las radiografias que encuentra con criterios (incluso si no tieneen enf asociada) contador = 0 columnNames = {} if(len(lista) != 0): resultQuery = askDb(queryMostrar,(tuple(lista),)) resultQuery2 = askDb(metaquery,(tuple(lista),)) for index,name in enumerate(resultQuery2): columnNames[index] = name[0] for element in resultQuery: temp = zip(element,range(len(element))) tempDic = {} for atomicVal in temp: print atomicVal tempDic[str(columnNames[atomicVal[1]])] = str(atomicVal[0]) data[str(contador)] = tempDic contador+=1 self.model.setupModel({}) self.model.importDict(data) self.table.redrawTable() self.b.setValues(0) return
def findTermFrequencies(self): """ Method for calculating the frequencies of each term in the tweets. """ if not os.path.isfile(self.TwitterKeysFile): tkMessageBox.showerror( "ERROR", "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.", parent=self.parent) return self.count += 1 if self.termFrequenciesOpenedFlag == False: # set window opened self.termFrequenciesOpenedFlag = True # initialize window global TermFrequenciesWindow def toggleFlag(): self.termFrequenciesOpenedFlag = False TermFrequenciesWindow.destroy() TermFrequenciesWindow = tk.Toplevel(self) TermFrequenciesWindow.minsize(500, 500) #TwitterKeysWindow.overrideredirect(True) TermFrequenciesWindow.geometry("500x500+100+100") TermFrequenciesWindow.title("Term Frequencies (only > 0.5%)") TermFrequenciesWindow.config(bd=5) TermFrequenciesWindow.protocol("WM_DELETE_WINDOW", toggleFlag) # create a new TableModel for table data model = TableModel() # create a new TableCanvas for showing the table table = TableCanvas(TermFrequenciesWindow, model=model, editable=False) table.createTableFrame() # dictionary for storing table data tableData = {} # calculate frequencies freqs = {} total = 0 outfile = open(self.TwitterStreamFile) for line in outfile: json_obj = json.loads(line) try: text = json_obj['text'].decode('utf-8') # clean the text text = ' '.join( re.sub( "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", "", text).split()) text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE) text = re.sub(r'RT', '', text, flags=re.MULTILINE) #print text text_list = text.split(' ') for char in text_list: if char.isalnum(): if char not in freqs: freqs[char] = 1 else: freqs[char] += 1 total += 1 except: #print "passed" pass for key in freqs.keys(): if freqs[key] / float(total) > 0.005: # insert frequencies into the table dictionary tableData[uuid.uuid4()] = { 'Term': key, 'Frequency (%)': str(round((freqs[key] / float(total)) * 100, 2)) } #print key + " " + str(freqs[key]/float(total)) # insert and sort data in the table model.importDict(tableData) #sort in descending order model.setSortOrder(columnIndex=1, reverse=1) table.adjustColumnWidths() table.resizeColumn(0, 200) table.resizeColumn(1, 200) table.redrawTable()
class StatisticDialog(Toplevel): def __init__(self, parent, statistic, stat_count_row): Toplevel.__init__(self, parent) self.withdraw() self.body(statistic, stat_count_row) self.deiconify() self.transient(parent) self.parent = parent self.title(_("win_statistic_title")) self.resizable(True, True) self.set_size() self.wait_visibility() # window needs to be visible for the grab self.grab_set() self.protocol("WM_DELETE_WINDOW", self.on_destroy) self.focus_set() self.wait_window(self) def set_size(self): sc_width = self.winfo_screenwidth() sc_height = self.winfo_screenheight() width = min(self.table_detailed_stat.get_totalWidth(), sc_width) height = min(750, sc_height) x = (sc_width - width) / 2 y = (sc_height - height) / 2 y = max(y - 20, 0) self.wm_geometry("%dx%d+%d+%d" % (width, height, x, y)) def on_destroy(self, event=None): self.parent.focus_set() self.destroy() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_pers"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_pers"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_pers_suc"), typedata='percent', align='right', max_val=u"100.0 %") self.model_ru_en.add_column(_("clm_state"), typedata='text', align='left', max_val=_("st_study") + u" ") for row in statistic.get_ru_en(): self.model_ru_en.add_row(row) self.model_ru_en.sort(6, False) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_pers_suc"), typedata='percent', align='right') self.model_en_ru.add_column(_("clm_state"), typedata='text', align='left') for row in statistic.get_en_ru(): self.model_en_ru.add_row(row) self.model_en_ru.sort(6, False) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append(Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def body(self, statistic, stat_count_row): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en() def draw_callback(self, row, col, celltxt, clr): if col == 6: words = [_("st_learned"), _("st_study"), _("st_learn")] ind = int(celltxt) return words[ind], clr_stat[ind] else: return celltxt, clr def show_ru_en(self): if self.last_button != 0: self.button_sel(0) self.table_detailed_stat.setModel(self.model_ru_en) self.frame_common_stat.grid_forget() self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_detailed_stat.do_bindings() def show_en_ru(self): if self.last_button != 1: self.button_sel(1) self.table_detailed_stat.setModel(self.model_en_ru) self.frame_common_stat.grid_forget() self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_detailed_stat.do_bindings() def show_common_stat(self): if self.last_button != 2: self.button_sel(2) self.frame_detailed_stat.grid_forget() self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_common_stat.do_bindings()
class TableController: """ Class that contains all methods to handle with choosen table menu with following functionality: add, modify, delete record, sort by columns, find record""" def __init__(self, tableName, database, themeWindow, returnEvent): self.tableName = tableName self.database = database self.themeWindow = themeWindow # Start logger self.logger = Logger(__name__, loggingLevel="debug") self.logger.debug("TableController logger has started.") self.addWindow = None self.modifyWindow = None self.columnNames = self.database.getColumns(tableName) self.tableData = self.database.getRawData(tableName) self.data = self.database.getData(tableName) self.model = TableModel() if len(self.data) == 0: messagebox.showwarning("Empty table", "This table has no records!") self.data["_"] = dict() self.data["_"]["_"] = "Empty table" else: for key, records in self.data.items(): for col, value in records.items(): if isinstance(value, datetime.date): self.data[key][col] = str(value) self.model.importDict(self.data) # Widgets self.content = Frame(self.themeWindow, bg="#B7B9B8", bd=4, relief=RAISED, width=self.themeWindow.winfo_width() - 80, height=self.themeWindow.winfo_height() - 80) self.content.place(x=40, y=40) self.content.grid(row=0, column=0) self.content.bind("<<goback>>", lambda _: returnEvent(None)) self.content.update() # Canvas with options menu self.topCanvas = Canvas(self.content, bg="white", bd=1, relief=RAISED, width=int(self.content.winfo_width()), height=int(self.content.winfo_height() / 12)) self.topCanvas.pack(fill='both', side=TOP) self.backButton = Button(self.topCanvas, text=" < ", command=self.back, width=9) self.backButton.pack(fill='both', side=LEFT) self.showButton = Button(self.topCanvas, text="Refresh table", command=self.refreshTable, width=22) self.showButton.pack(fill='both', side=LEFT) # Canvas with data self.middleFrame = Frame(self.content) self.middleFrame.pack(fill='both', side=TOP) self.table = CustomTable(self.middleFrame, model=self.model) self.table.show() # Canvas with DML buttons self.bottomCanvas = Canvas(self.content, bg="white", bd=1, relief=FLAT, width=int(self.content.winfo_width()), height=int(self.content.winfo_height() / 5)) self.bottomCanvas.pack(fill='both', side=TOP) self.buttonAdd = Button(self.bottomCanvas, text=" ADD ", command=self.add, width=24, height=3, bd=5) self.buttonAdd.pack(side=LEFT) self.buttonModify = Button(self.bottomCanvas, text=" MODIFY ", command=self.modify, width=25, height=3, bd=5) self.buttonModify.pack(side=LEFT) self.buttonDelete = Button(self.bottomCanvas, text=" DELETE ", command=lambda: self.delete(self.tableName), width=25, height=3, bd=5) self.buttonDelete.pack(side=LEFT) def back(self): """ Go back to main window """ self.content.event_generate("<<goback>>") def backEvent(self, event): if self.addWindow is not None: self.addWindow.addWindow.destroy() self.addWindow = None if self.modifyWindow is not None: self.modifyWindow.modifyWindow.destroy() self.modifyWindow = None self.refreshTable() def add(self): """ Go to add window """ if self.addWindow is None: self.logger.debug("Starting add window.") self.addWindow = AddController(self.themeWindow, self.tableName, self.database, self.backEvent) def modify(self): """ Go to modify window """ if self.table.startrow != self.table.endrow: messagebox.showwarning('Modify error', 'Please select only one record!') else: selectedRow = self.table.currentrow if self.modifyWindow is None: self.logger.debug("Starting modify window.") self.modifyWindow = ModifyController( self.themeWindow, self.tableName, self.database, self.model.getRecName(selectedRow), self.data, self.backEvent) def delete(self, tableName): """ Delete selected records """ for no, i in enumerate(self.table.multiplerowlist): recName = self.model.getRecName(i) deletedRecord = list() for column, value in self.data[recName].items(): deletedRecord.append(value) try: self.database.deleteRecord(tableName, deletedRecord) except Exception as e: self.logger.error( f"Can not delete selected records! Error = {e}") errorNo = int(e.__str__().split()[0][1:-1]) if errorNo == 1451: messagebox.showerror( "Can not delete selected records!", f"There are bounds including selected record.") else: messagebox.showerror("Can not delete selected records!", f"Error {e}") return confirm = messagebox.askyesno( "Deleting record confirmation", f"Are You sure that You want to delete {len(self.table.multiplerowlist)} records?" ) if confirm: self.database.connection.commit() else: self.database.connection.rollback() self.model.createEmptyModel() self.refreshTable() return def refreshTable(self): self.data = self.database.getData(self.tableName) if len(self.data) == 0: messagebox.showwarning("Empty table", "This table has no records!") self.data["_"] = dict() self.data["_"]["_"] = "Empty table" else: for key, records in self.data.items(): for col, value in records.items(): if isinstance(value, datetime.date): self.data[key][col] = str(value) self.model.importDict(self.data) self.table.redraw()
def __init__(self, tableName, database, themeWindow, returnEvent): self.tableName = tableName self.database = database self.themeWindow = themeWindow # Start logger self.logger = Logger(__name__, loggingLevel="debug") self.logger.debug("TableController logger has started.") self.addWindow = None self.modifyWindow = None self.columnNames = self.database.getColumns(tableName) self.tableData = self.database.getRawData(tableName) self.data = self.database.getData(tableName) self.model = TableModel() if len(self.data) == 0: messagebox.showwarning("Empty table", "This table has no records!") self.data["_"] = dict() self.data["_"]["_"] = "Empty table" else: for key, records in self.data.items(): for col, value in records.items(): if isinstance(value, datetime.date): self.data[key][col] = str(value) self.model.importDict(self.data) # Widgets self.content = Frame(self.themeWindow, bg="#B7B9B8", bd=4, relief=RAISED, width=self.themeWindow.winfo_width() - 80, height=self.themeWindow.winfo_height() - 80) self.content.place(x=40, y=40) self.content.grid(row=0, column=0) self.content.bind("<<goback>>", lambda _: returnEvent(None)) self.content.update() # Canvas with options menu self.topCanvas = Canvas(self.content, bg="white", bd=1, relief=RAISED, width=int(self.content.winfo_width()), height=int(self.content.winfo_height() / 12)) self.topCanvas.pack(fill='both', side=TOP) self.backButton = Button(self.topCanvas, text=" < ", command=self.back, width=9) self.backButton.pack(fill='both', side=LEFT) self.showButton = Button(self.topCanvas, text="Refresh table", command=self.refreshTable, width=22) self.showButton.pack(fill='both', side=LEFT) # Canvas with data self.middleFrame = Frame(self.content) self.middleFrame.pack(fill='both', side=TOP) self.table = CustomTable(self.middleFrame, model=self.model) self.table.show() # Canvas with DML buttons self.bottomCanvas = Canvas(self.content, bg="white", bd=1, relief=FLAT, width=int(self.content.winfo_width()), height=int(self.content.winfo_height() / 5)) self.bottomCanvas.pack(fill='both', side=TOP) self.buttonAdd = Button(self.bottomCanvas, text=" ADD ", command=self.add, width=24, height=3, bd=5) self.buttonAdd.pack(side=LEFT) self.buttonModify = Button(self.bottomCanvas, text=" MODIFY ", command=self.modify, width=25, height=3, bd=5) self.buttonModify.pack(side=LEFT) self.buttonDelete = Button(self.bottomCanvas, text=" DELETE ", command=lambda: self.delete(self.tableName), width=25, height=3, bd=5) self.buttonDelete.pack(side=LEFT)
def findTweetSentiment(self): """ Method for calculating the sentiment of each tweet. """ if not os.path.isfile(self.TwitterKeysFile): tkMessageBox.showerror( "ERROR", "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.", parent=self.parent) return self.count += 1 if self.tweetSentimentOpenedFlag == False: # set window opened self.tweetSentimentOpenedFlag = True # initialize window global TweetSentimentWindow def toggleFlag(): self.tweetSentimentOpenedFlag = False TweetSentimentWindow.destroy() TweetSentimentWindow = tk.Toplevel(self) TweetSentimentWindow.minsize(600, 500) #TwitterKeysWindow.overrideredirect(True) TweetSentimentWindow.geometry("1000x500+100+100") TweetSentimentWindow.title( "Tweet Sentiments (Zero values omitted)") TweetSentimentWindow.config(bd=5) TweetSentimentWindow.protocol("WM_DELETE_WINDOW", toggleFlag) # create a new TableModel for table data model = TableModel() # create a new TableCanvas for showing the table table = TableCanvas(TweetSentimentWindow, model=model, editable=False) table.createTableFrame() # dictionary for storing table data tableData = {} # calculate sentiments afinnfile = open(self.AFINNFile) scores = {} for line in afinnfile: term, score = line.split("\t") scores[term] = int(score) #print scores.items() positive = 0.0 negative = 0.0 outfile = open(self.TwitterStreamFile) for line in outfile: json_obj = json.loads(line) sentiment = 0 try: text = json_obj['text'].decode('utf-8') # clean the text text = ' '.join( re.sub( "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", "", text).split()) text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE) text = re.sub(r'RT', '', text, flags=re.MULTILINE) #print text text_list = text.split(' ') for char in text_list: if char in scores: sentiment += scores[char] if sentiment != 0: # add items to table data dictionary tableData[uuid.uuid4()] = { 'Tweet': text, 'Score': str(sentiment) } if sentiment > 0: positive += 1 elif sentiment < 0: negative += 1 #print text + " " + str(sentiment) + "\n\n" except: #print "passed" pass # calculate ratio if positive > 0 and negative > 0: ratio = round(float(positive) / float(negative), 2) # insert and sort data in the table model.importDict(tableData) table.resizeColumn(0, 850) table.resizeColumn(1, 50) table.sortTable(columnName='Score') table.redrawTable() if positive > negative: extra = "The overall sentiment is POSITIVE." else: extra = "The overall sentiment is NEGATIVE." # show info box about the overall result tkMessageBox.showinfo( "Score Ratio", "The ratio of positive vs. negative tweets is " + str(ratio) + ". " + extra, parent=TweetSentimentWindow)
def findTermFrequencies(self): """ Method for calculating the frequencies of each term in the tweets. """ if not os.path.isfile(self.TwitterKeysFile): tkMessageBox.showerror("ERROR", "Twitter API credentials not filled. Use the Set/Update Twitter Credentials button to do so.", parent = self.parent) return self.count += 1 if self.termFrequenciesOpenedFlag == False: # set window opened self.termFrequenciesOpenedFlag = True # initialize window global TermFrequenciesWindow def toggleFlag(): self.termFrequenciesOpenedFlag = False TermFrequenciesWindow.destroy() TermFrequenciesWindow = tk.Toplevel(self) TermFrequenciesWindow.minsize(500, 500) #TwitterKeysWindow.overrideredirect(True) TermFrequenciesWindow.geometry("500x500+100+100") TermFrequenciesWindow.title("Term Frequencies (only > 0.5%)") TermFrequenciesWindow.config(bd=5) TermFrequenciesWindow.protocol("WM_DELETE_WINDOW", toggleFlag) # create a new TableModel for table data model = TableModel() # create a new TableCanvas for showing the table table = TableCanvas(TermFrequenciesWindow, model=model, editable=False) table.createTableFrame() # dictionary for storing table data tableData = {} # calculate frequencies freqs = {} total = 0 outfile = open(self.TwitterStreamFile) for line in outfile: json_obj = json.loads(line) try: text = json_obj['text'].decode('utf-8') # clean the text text = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)","",text).split()) text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE) text = re.sub(r'RT', '', text, flags=re.MULTILINE) #print text text_list = text.split(' ') for char in text_list: if char.isalnum(): if char not in freqs: freqs[char] = 1 else: freqs[char] += 1 total += 1 except: #print "passed" pass for key in freqs.keys(): if freqs[key]/float(total) > 0.005: # insert frequencies into the table dictionary tableData[uuid.uuid4()] = {'Term': key, 'Frequency (%)': str(round((freqs[key]/float(total))*100, 2))} #print key + " " + str(freqs[key]/float(total)) # insert and sort data in the table model.importDict(tableData) #sort in descending order model.setSortOrder(columnIndex = 1, reverse = 1) table.adjustColumnWidths() table.resizeColumn(0, 200) table.resizeColumn(1, 200) table.redrawTable()
class _StatisticDialog(TopDialog): def __init__(self, parent, factory, statistic, stat_count_row): TopDialog.__init__(self, parent, (statistic, stat_count_row)) self.factory = factory self.title(_("win_statistic_title")) self.wait_visibility() self.set_size(self.table_detailed_stat.get_totalWidth(), 750) self.resizable(True, True) self.grab_set() self.run() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append(Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def init_window(self, (statistic, stat_count_row)): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en()