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 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 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 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 __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
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()
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
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 table.redrawTable() #by column name raw_input('Sort table by column name') table.sortTable(columnName='label') #by column index raw_input('Sort table by column index') table.sortTable(columnIndex=1) raw_input('Add automatic key row') #add with automatic key table.addRow()
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()
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 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)
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()
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()
class TelemetryPanel(observer.Observer): ''' This panel is a table of currently observed telemetry channels. ''' 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 = [] def __handle_column_motion(self, event): """ Used to rebind the table's ColumnHeader <B1-Motion> event. """ try: self.__table.tablecolheader.handle_mouse_drag(event) except ValueError, e: pass
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 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()