Ejemplo n.º 1
0
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()
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
class createTable(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.place(x=0, y=100, relwidth=1, relheight=1)
        # self.grid()
        self.F = tk.Frame(self)
        self.F.grid(sticky=tk.N + tk.S + tk.W)
        # self.F.place(x=10,y=10)
        self.createWidgets()

    def createWidgets(self):
        self.table = TableCanvas(self.F,
                                 rows=0,
                                 cols=0,
                                 width=350,
                                 height=150,
                                 editable=False,
                                 cellwidth=175)
        self.table.createTableFrame()
        data = database.get_data_file(username1)
        print data
        if len(data) != 0:
            for i in range(len(data)):
                for j in range(2):
                    if j == 0:
                        data_1 = data[i][j]
                    if j == 1:
                        data_2 = data[i][j]
                keyname = "rec" + str(i)
                self.table.addRow(
                    keyname, **{
                        'Name of File': data_2,
                        'Date of created': data_1
                    })
            self.table.redrawTable()
        else:
            keyname = "1"
            data_2 = "no file in storage"
            self.table.addRow(
                keyname, **{
                    'Name of File': data_2,
                    'Date of created': data_2
                })
            self.table.redrawTable()
Ejemplo n.º 4
0
    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()  
Ejemplo n.º 5
0
Archivo: 1.py Proyecto: rishabh279/MRS
class Application(Frame):
    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 create_widgets(self):
        self.table.model.load('save.table')  #You don't have to load a model, but I usually
        self.table.redrawTable()             #Create a base model for my tables.

        d = dir(self.table)  #Will show you what you can do with tables.  add .model
                             #to the end to see what you can do with the models.
        for i in d:
            print i

    def clicked(self, event):  #Click event callback function.
        #Probably needs better exception handling, but w/e.
        try:
            rclicked = self.table.get_row_clicked(event)
            cclicked = self.table.get_col_clicked(event)
            clicks = (rclicked, cclicked)
            print 'clicks:', clicks
        except: 
            print 'Error'
        if clicks:
            #Now we try to get the value of the row+col that was clicked.
            try: print 'single cell:', self.table.model.getValueAt(clicks[0], clicks[1])
            except: print 'No record at:', clicks

            #This is how you can get the entire contents of a row.
            try: print 'entire record:', self.table.model.getRecordAtRow(clicks[0])
            except: print 'No record at:', clicks
Ejemplo n.º 6
0
    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()
Ejemplo n.º 7
0
    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)
Ejemplo n.º 8
0
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
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('')
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
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
table.redrawTable()

Ejemplo n.º 12
0
    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()
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
'''
root=Tk()
main_f=Frame(root)
main_f.pack()
table = TableCanvas(main_f)
table.createTableFrame()
'''
导入数据
'''

model = table.model
#model.importDict(data) #can import from a dictionary to populate model
table.load("1.table")
table.model.data[0]['Model']='test'
table.model.data[6]['Model']='test6'
table.redrawTable()
def updatetable(filename):
    f=open(filename,'r')
    for lineno,line in enumerate(f):
        if lineno == 0:
           continue
        else:
            rowid=lineno-1
            elements=line.strip().split()
            print elements
            table.model.data[rowid]['Model']=elements[0]
            table.model.data[rowid]['Qty']=elements[1]
            table.model.data[rowid]['Time']=elements[2]
    table.redrawTable()
    main_f.after(5000,updatetable,"table_input.txt")
main_f.after(5000,updatetable,"table_input.txt")
Ejemplo n.º 15
0
class MainWindow(object):
    def __init__(self, controller):
        self.controller = controller
        self.window = Tk()
        # self.window.geometry('1600x' + str(self.window.winfo_screenheight()))
        self.window.geometry(config.MAIN_WINDOW_DEFAULT_WIDTH + 'x' + config.MAIN_WINDOW_DEFAULT_HEIGHT)
        self.window.bind_all('<Key>', self.key)
        self.frame = Frame(self.window, width=200, height=200, bd=11)
        self.frame.pack(expand=True, fill=BOTH)
        self.label_value = StringVar()
        self.label_value.set('test')
        self.label = Label(self.frame, textvariable=self.label_value, anchor=NW, justify=CENTER, wraplength=398)
        # don't mix grid and pack
        self.label.grid(row=0)
        self.table = TableCanvas(self.frame, cols=0, rows=0, editable=False)

        self.table.parentframe.master.bind_all("<Control-j>", self.move_cursor_up)
        self.table.parentframe.master.bind_all("<Control-k>", self.move_cursor_down)
        self.table.parentframe.master.bind_all("<Control-l>", self.move_cursor_left)
        self.table.parentframe.master.bind_all("<Control-semicolon>", self.move_cursor_right)

        self.table.createTableFrame()

        self.sort_order = 0
        # self.window.mainloop()

    def key(self, event):
        if event.keysym == 'Escape':
            self.window.destroy()
            return
        elif event.keysym == 'Return':
            return
        else:
            # self.label_value.set(self.controller.query_builder.get_query_for_label())
            self.controller.key_pressed_event(event.keysym)
            return

    def set_data_to_table(self, dct, sortColumn=''):
        if not dct:
            return
        self.table.model.createEmptyModel()
        self.table.model.importDict(dct)
        self.table.sortTable(columnName=sortColumn)
        self.table.redrawTable()

    def sort_table(self, sortColumn):
        self.table.sortTable(columnName=sortColumn, reverse=self.sort_order)
        if self.sort_order == 0:
            self.sort_order = 1
        else:
            self.sort_order = 0

    def move_cursor_up(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentrow == 0:
            return
        else:
            self.table.currentrow = self.table.currentrow -1

        self.draw_table_cursor()
        return

    def move_cursor_down(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentrow >= self.table.rows-1:
            return
        else:
            self.table.currentrow = self.table.currentrow +1

        self.draw_table_cursor()
        return

    def move_cursor_left(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        self.table.currentcol  = self.table.currentcol -1

        self.draw_table_cursor()
        return

    def move_cursor_right(self, event):
        x,y = self.table.getCanvasPos(self.table.currentrow, 0)
        if x == None:
            return

        if self.table.currentcol >= self.table.cols-1:
            if self.table.currentrow < self.table.rows-1:
                self.table.currentcol = 0
                self.table.currentrow  = self.table.currentrow +1
            else:
                return
        else:
            self.table.currentcol  = self.table.currentcol +1

        self.draw_table_cursor()
        return

    def draw_table_cursor(self):
        self.table.drawSelectedRect(self.table.currentrow, self.table.currentcol)
        coltype = self.table.model.getColumnType(self.table.currentcol)
        if coltype == 'text' or coltype == 'number':
            self.table.delete('entry')
            self.table.drawCellEntry(self.table.currentrow, self.table.currentcol)
Ejemplo n.º 16
0
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()
Ejemplo n.º 17
0
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