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 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()
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()
def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.model = TableModel() self.table = TableCanvas(self, model=self.model) self.table.createTableFrame() root.bind('<ButtonRelease-1>', self.clicked) #Bind the click release event self.create_widgets()
def __init__(self, master, **kwargs): TableCanvas.__init__(self, master, editable=False, rowheaderwidth=0, cellwidth=60, cellbackgr='#CCCC99', **kwargs) # 取消其預設的事件 self.unbind_all("<Delete>") self.unbind_all('<Return>') self.unbind_all('<Control-x>') self.unbind_all('<Control-c>') self.unbind_all('<Control-v>')
def draw(tab_arrive,temps_file,temp_system): dictio={} j=0 for i in range(len(tab_arrive)): dictio2={} dictio2["t_arrive"]='{:.4f}'.format(tab_arrive[i]) dictio2["t_file"]='{:.4f}'.format(temps_file[i]) dictio2["t_service"]='{:.4f}'.format(tab_arrive[i]+temps_file[i]) dictio2["t_depart"]='{:.4f}'.format(tab_arrive[i]+temp_system[i]) j=i+1 dictio[j]=dictio2 master = Tk() tframe = Frame(master) tframe.pack() table = TableCanvas(tframe) table = TableCanvas(tframe, data=dictio) model = table.model model.importDict(dictio) table.sortTable(columnName="t_arrive") table.show() master.mainloop()
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 initTable(self, ev = None): self.tableFrame = Tkinter.Frame(self.top) self.tableFrame.pack(expand = True, fill = Tkinter.BOTH) # 后期修改 self.top.geometry('920x700+200+100') self.model = TableModel(rows = 0, columns = 0) # like HTML self.bookTable = TableCanvas(self.tableFrame, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial',12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS self.bookTable.createTableFrame() self.colnames = ('ISBN', '书名', '作者', '出版社', '出版时间', '价格') for name in self.colnames: self.bookTable.addColumn(name) self.bookTable.addRows(1) self.bookTable.autoResizeColumns()
def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_pers_suc"), typedata='percent', align='right', max_val=u"100.0 %") self.model_ru_en.add_column(_("clm_state"), typedata='text', align='left', max_val=_("st_study") + u" ") for row in statistic.get_ru_en(): self.model_ru_en.add_row(row) self.model_ru_en.sort(6, False) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_pers_suc"), typedata='percent', align='right') self.model_en_ru.add_column(_("clm_state"), typedata='text', align='left') for row in statistic.get_en_ru(): self.model_en_ru.add_row(row) self.model_en_ru.sort(6, False) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width
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()
def _initHelpMenu(): #~ help menu helpmenu = Menu(menubar, tearoff=False) helpmenu.add_command(label="Help Docs",command=hello) helpmenu.add_command(label="About",command=about) menubar.add_cascade(label="Help",menu=helpmenu) master.config(menu=menubar) #~ start and stopmenu startmenu = Menu(menubar, tearoff=False) startmenu.add_command(label="Start",command=video_start) startmenu.add_command(label="Stop",underline=0,command=video_stop,accelerator="Ctrl+Q") menubar.add_cascade(label="Run",underline=0,menu=startmenu) master.config(menu=menubar) master.bind('<Shift-Q>', video_stop) figureShowFrame = Figure(figsize=(4, 4), dpi=100) axesFrame = figureShowFrame.add_subplot(111) figureShowFrame.suptitle("ORINGS") axesFrame.clear() #~ hIm = axesFrame hIm = axesFrame.imshow(frame, interpolation='nearest', cmap = cm.Greys_r, vmin=20, vmax=80, animated=True) canvasShowFrame = FigureCanvasTkAgg(figureShowFrame , master=master) canvasShowFrame.get_tk_widget().place(x=150, y=100) #~ x_codnte = np.arange(0, 100, 1) #~ y_codnte = np.array([0] * 100) figureShowContour = Figure(figsize=(4, 4), dpi=100) axesContour = figureShowContour.add_subplot(111) figureShowContour.suptitle("CONTOUR PLOTS") canvasShowContour = FigureCanvasTkAgg(figureShowContour, master=master) canvasShowContour.get_tk_widget().place(x=750, y=100) frame_value = Frame(master) frame_value.pack() frame_value.place(x=500, y=550,width=300, height=70) model = TableModel() table = TableCanvas(frame_value, model=model, editable=False) table.createTableFrame()
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 init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [ row_name[i] + it for i, it in enumerate(statistic.get_common_stat()) ]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget()
def 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()
def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_pers"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_pers"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget()
def initialize(self): mainframe = Frame(self,padx=3, pady=12) mainframe.grid(column=0, row=0, sticky=(N,E,W,S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.minsize(400, 400) subframe = Frame(mainframe) subframe.grid(row=0, column=0, sticky="NW") label = Label(subframe, text="Stock Symbol : ") label.pack(side="left") mainframe.symTextIn = Entry(subframe) self.sysmTextIn = mainframe.symTextIn self.sysmTextIn.bind("<Return>", self.addStock) mainframe.symTextIn.pack(side="left") addButton = Button(subframe,text=u"Add", command=self.addStock) addButton.pack(side="left", pady=5, padx=5) blueRow = Label(mainframe,fg="white",bg="blue") blueRow.grid(column=0,row=1,columnspan=3,sticky=(E,W)) mainframe.columnconfigure(0, weight=1) self.tableframe = Frame(mainframe, height=200, width=200, background="black") self.tableframe.grid(column=0, row=2,columnspan=3, sticky=(N,E,W,S)) mainframe.rowconfigure(2, weight=1) mainframe.columnconfigure(0, weight=1) mainframe.bind("<Return>", self.addStock) self.sysmTextIn.focus() #Create column Headers. self.model = TableModel(newdict=self.Objcolumn.getColumnsDict()) self.table = TableCanvas(self.tableframe, model=self.model, cols=len(self.Objcolumn.getColumns()),thefont=('Arial',9), rowheight=18, cellwidth=80, editable=False, selectedcolor='white', rowselectedcolor='white', autoresizecols=0, inset=0, width=350) self.model.importDict({'rec0' : {'Symbol' : ' ', 'Last Price':' ', 'Change':' ','%Change':' ' #,'Prev Close':' ','Bid':' ','Ask':' ' }}) self.table.createTableFrame() self.table.redrawTable()
def __init__(self, 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
def _frame2(): frame.destroy() frame2 = tk.Tk() frame2.title('Frame2') frame2.geometry('1000x300') tframe = Frame(frame2) tframe.pack() datafrommssql() table = TableCanvas(tframe, editable=False, read_only=True, rows=5, cols=5, height=110, width=939) table.importCSV('test.csv') Entry(frame2, text='', textvariable=id1).pack() Button(frame2, text="Buy car", command=buy).pack() table.show()
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 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
def __init__(self, frame, usable_width, direction): self.deleted = False self.directed = direction self.ftable = Frame(frame.ftables) self.ft = Frame(self.ftable) self.fnp = Frame(self.ftable) #frame network properties if(usable_width > 1500) : button_width=17 button_width_plot=7 font=('Verdana',9) image_button = 23 list_fonts = list( tkFont.families() ) elif(usable_width > 1200): button_width=15 button_width_plot=6 image_button = 28 font=('Verdana',10) else: button_width=14 button_width_plot=5 image_button = 28 font=('Verdana',8) if(usable_width > 1500): self.save_img = PhotoImage(file="save.gif") self.load_img = PhotoImage(file="load.gif") self.delete_img = PhotoImage(file="delete.gif") elif(usable_width > 1200): self.save_img = PhotoImage(file="save22.gif") self.load_img = PhotoImage(file="load22.gif") self.delete_img = PhotoImage(file="delete.gif") else: self.save_img = PhotoImage(file="save20.gif") self.load_img = PhotoImage(file="load20.gif") self.delete_img = PhotoImage(file="delete.gif") labelfnp_width = 10 pos = 0 # buttons area for the right panel of each graph self.buttonSave = Button(master=self.fnp, image=self.save_img, command=lambda num=frame.number_table: save_network(frame, num), relief=FLAT, width=image_button) self.buttonSave.image = self.save_img self.buttonSave.grid(row=0, column=0, pady=1, padx=1) self.buttonDelete = Button(master=self.fnp, image=self.delete_img, command=lambda num=frame.number_table: delete_network(frame, num), relief=FLAT, width=image_button) self.buttonDelete.image = self.delete_img self.buttonDelete.grid(row=pos, column=1, pady=1, padx=1) pos += 1 self.plot_button = Button(master=self.fnp, text='Plot', command=lambda num=frame.number_table: plot_graph(frame, num), width=button_width) self.plot_button.grid(row=pos, column=0, columnspan=2, pady=2, padx=5) pos += 1 self.netPro_label = Label(self.fnp, text="Network properties:", width=3*labelfnp_width, anchor=CENTER) self.netPro_label.grid(row=pos, column=0, columnspan=2, pady=2, padx=5) pos += 1 self.number_nodesLabel = Label(self.fnp, text="Nodes: ", width=labelfnp_width, anchor=W) self.number_nodesLabel.grid(row=pos, column=0, pady=2, padx=5) self.number_nodes_str = StringVar() self.number_nodes_l = Label(self.fnp, textvariable=self.number_nodes_str, width=labelfnp_width, anchor=W) self.number_nodes_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.number_arcsLabel = Label(self.fnp, text="Arcs: ", width=labelfnp_width, anchor=W) self.number_arcsLabel.grid(row=pos, column=0, pady=2, padx=5) self.number_arcs_str = StringVar() self.number_arcs_l = Label(self.fnp, textvariable=self.number_arcs_str, width=labelfnp_width, anchor=W) self.number_arcs_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.number_diameterLabel = Label(self.fnp, text="Diameter: ", width=labelfnp_width, anchor=W) self.number_diameterLabel.grid(row=pos, column=0, pady=2, padx=5) self.diameter_str = StringVar() self.diameter_l = Label(self.fnp, textvariable=self.diameter_str, width=labelfnp_width, anchor=W) self.diameter_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.assortativityLabel = Label(self.fnp, text="Assortativity: ", width=labelfnp_width, anchor=W) self.assortativityLabel.grid(row=pos, column=0, pady=2, padx=5) self.assortativity_str = StringVar() self.assortativity_l = Label(self.fnp, textvariable=self.assortativity_str, width=labelfnp_width, anchor=W) self.assortativity_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.entropyLabel = Label(self.fnp, text="Entropy: ", width=labelfnp_width, anchor=W) self.entropyLabel.grid(row=pos, column=0, pady=2, padx=5) self.entropy_str = StringVar() self.entropy_l = Label(self.fnp, textvariable=self.entropy_str, width=labelfnp_width, anchor=W) self.entropy_l.grid(row=pos, column=1, pady=2, padx=5) pos += 1 self.subgraph_ind_sub = Button(master=self.fnp, text='Induced subgraph', font=font, command=lambda num=frame.number_table: induced_subgraph(frame, num, usable_width), width=button_width) self.subgraph_ind_sub.grid(row=pos, column=0, pady=2, padx=5) pos+=1 self.subgraph_ind_sub_lev = Button(master=self.fnp, text='Subgraph level', font=font, command=lambda num=frame.number_table: subgraph_levels(frame, num, usable_width), width=button_width) self.subgraph_ind_sub_lev.grid(row=pos, column=0, pady=2, padx=5) self.frame_but = Frame(self.fnp) #table part, create and fill columns self.columnNames = columnNames self.model = TableModel() self.model.data = {} for i in xrange(len(self.columnNames)): if(direction): if(columnNames[i] != "Information centrality"): self.model.addColumn(self.columnNames[i]) else: if(columnNames[i] != 'Eccentricity in'): if(columnNames[i] != 'Vibrational centrality in'): if(columnNames[i] != 'In degree'): if(columnNames[i] != 'Total degree'): self.model.addColumn(self.columnNames[i].replace(" out", "").replace("Out degree", "Degree")) if(usable_width > 1500): thefont=30 rowheight=22 else: thefont=5 rowheight=20 self.table = TableCanvas(self.ft, model=self.model, rows=0, cols=0, rowheaderwidth=0, rowheight=rowheight, cellbackgr='#ffffff', thefont=thefont, editable=False, showkeynamesinheader=True, autoresizecols=True, fill=X) self.model.addRow() self.table.createTableFrame() self.file_name = StringVar() self.file_name_label = Label(self.ftable, textvariable=self.file_name) self.file_name_label.pack(side=TOP) self.ft.pack(side=LEFT, expand=True, fill=X) self.fnp.pack(side=RIGHT) self.ftable.pack(expand=True, fill=X) #create the centrality list self.centrality = [[] for x in xrange(len(self.columnNames))] self.table.fontsize=thefont self.table.setFontSize() self.adj_matrix = None self.laplacian_psinv = None frame.canvas.config(scrollregion=frame.canvas.bbox("all"))
class Watchlist(Tk): def __init__(self,parent): Tk.__init__(self,parent) self.parent = parent self.currentRow = 1 self.rows = [] self.Objcolumn = Columns() self.initialize() def addStock(self, args=None): stockSym = self.sysmTextIn.get() if stockSym == None: return else : self.addRow(stockSym) return def addRow(self, stockSym): self.sysmTextIn.delete(0, END) searchterms = [('Symbol', stockSym.upper(), '=', 'AND')] symbolCol = self.model.getColumnData(columnIndex=self.model.getColumnIndex(columnName="Symbol"), columnName="Symbol", filters=searchterms) if stockSym.upper() in symbolCol: return result = ystockquote.get_all(stockSym.upper()) row = Rows(result, stockSym.upper()) dictrow = row.getRow() colIndex = self.model.getColumnIndex(columnName="Symbol") stockSym = self.model.getValueAt(rowIndex=0, columnIndex=colIndex) if stockSym == " ": row0 = self.table.getSelectedRow() self.model.deleteRow(row0) self.table.setSelectedRow(row0-1) self.table.clearSelected() else: self.currentRow = self.currentRow + 1 self.model.importDict({ "%s%d" % ("rec", self.currentRow) : dictrow}) change = float(dictrow['Change']) if change > 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="Change"),color="green", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="green", key="fg") if change < 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="Change"),color="red", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex("%s%d" % ("rec", self.currentRow)), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="red", key="fg") self.table.redrawTable() self.after(5000, self.updateTableValue, "%s%d" % ("rec", self.currentRow)) def fadeIn(self, rec) : if rec not in self.model.data: return self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Last Price"),color="white") self.table.redrawTable() def updateTableValue(self, rec): increased = False decreased = False if rec not in self.model.data: return result = ystockquote.get_all(self.model.data[rec]['Symbol'].upper()) row = Rows(result, self.model.data[rec]['Symbol'].upper()) dictrow = row.getRow() change = float(dictrow['Change']) #print "update table value" + self.model.data[rec]['Symbol'].upper() if change > 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Change"),color="green", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="green", key="fg") if change < 0: self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Change"),color="red", key="fg") self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="%Change"),color="red", key="fg") if float(self.model.data[rec]['Last Price']) > float(dictrow['Last Price']): color="Red" decreased = True if float(self.model.data[rec]['Last Price']) < float(dictrow['Last Price']): color="Green" increased = True if (decreased == True) or (increased == True): self.model.setColorAt(rowIndex=self.model.getRecordIndex(rec), columnIndex=self.model.getColumnIndex(columnName="Last Price"),color=color) for col in self.model.data[rec]: self.model.data[rec][col] = dictrow[col] self.table.redrawTable() self.id = self.after(5000, self.updateTableValue, rec) self.id = self.after(1000, self.fadeIn, rec) def initialize(self): mainframe = Frame(self,padx=3, pady=12) mainframe.grid(column=0, row=0, sticky=(N,E,W,S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.minsize(400, 400) subframe = Frame(mainframe) subframe.grid(row=0, column=0, sticky="NW") label = Label(subframe, text="Stock Symbol : ") label.pack(side="left") mainframe.symTextIn = Entry(subframe) self.sysmTextIn = mainframe.symTextIn self.sysmTextIn.bind("<Return>", self.addStock) mainframe.symTextIn.pack(side="left") addButton = Button(subframe,text=u"Add", command=self.addStock) addButton.pack(side="left", pady=5, padx=5) blueRow = Label(mainframe,fg="white",bg="blue") blueRow.grid(column=0,row=1,columnspan=3,sticky=(E,W)) mainframe.columnconfigure(0, weight=1) self.tableframe = Frame(mainframe, height=200, width=200, background="black") self.tableframe.grid(column=0, row=2,columnspan=3, sticky=(N,E,W,S)) mainframe.rowconfigure(2, weight=1) mainframe.columnconfigure(0, weight=1) mainframe.bind("<Return>", self.addStock) self.sysmTextIn.focus() #Create column Headers. self.model = TableModel(newdict=self.Objcolumn.getColumnsDict()) self.table = TableCanvas(self.tableframe, model=self.model, cols=len(self.Objcolumn.getColumns()),thefont=('Arial',9), rowheight=18, cellwidth=80, editable=False, selectedcolor='white', rowselectedcolor='white', autoresizecols=0, inset=0, width=350) self.model.importDict({'rec0' : {'Symbol' : ' ', 'Last Price':' ', 'Change':' ','%Change':' ' #,'Prev Close':' ','Bid':' ','Ask':' ' }}) self.table.createTableFrame() self.table.redrawTable()
def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas( self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column( col).width = self.model_ru_en.get_column(col).width
class StatisticDialog(Toplevel): def __init__(self, parent, statistic, stat_count_row): Toplevel.__init__(self, parent) self.withdraw() self.body(statistic, stat_count_row) self.deiconify() self.transient(parent) self.parent = parent self.title(_("win_statistic_title")) self.resizable(True, True) self.set_size() self.wait_visibility() # window needs to be visible for the grab self.grab_set() self.protocol("WM_DELETE_WINDOW", self.on_destroy) self.focus_set() self.wait_window(self) def set_size(self): sc_width = self.winfo_screenwidth() sc_height = self.winfo_screenheight() width = min(self.table_detailed_stat.get_totalWidth(), sc_width) height = min(750, sc_height) x = (sc_width - width) / 2 y = (sc_height - height) / 2 y = max(y - 20, 0) self.wm_geometry("%dx%d+%d+%d" % (width, height, x, y)) def on_destroy(self, event=None): self.parent.focus_set() self.destroy() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_pers"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_pers"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_pers_suc"), typedata='percent', align='right', max_val=u"100.0 %") self.model_ru_en.add_column(_("clm_state"), typedata='text', align='left', max_val=_("st_study") + u" ") for row in statistic.get_ru_en(): self.model_ru_en.add_row(row) self.model_ru_en.sort(6, False) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_pers_suc"), typedata='percent', align='right') self.model_en_ru.add_column(_("clm_state"), typedata='text', align='left') for row in statistic.get_en_ru(): self.model_en_ru.add_row(row) self.model_en_ru.sort(6, False) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append(Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def body(self, statistic, stat_count_row): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en() def draw_callback(self, row, col, celltxt, clr): if col == 6: words = [_("st_learned"), _("st_study"), _("st_learn")] ind = int(celltxt) return words[ind], clr_stat[ind] else: return celltxt, clr def show_ru_en(self): if self.last_button != 0: self.button_sel(0) self.table_detailed_stat.setModel(self.model_ru_en) self.frame_common_stat.grid_forget() self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_detailed_stat.do_bindings() def show_en_ru(self): if self.last_button != 1: self.button_sel(1) self.table_detailed_stat.setModel(self.model_en_ru) self.frame_common_stat.grid_forget() self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_detailed_stat.do_bindings() def show_common_stat(self): if self.last_button != 2: self.button_sel(2) self.frame_detailed_stat.grid_forget() self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) self.table_common_stat.do_bindings()
command=lambda: search(trend_text, noOfTweets_text, saveFile_text.get(1.0, 'end'), progress)) search_button.place(relx=move_x+0.61, rely=0.3, relwidth=0.15, relheight=0.05) progress = ttk.Progressbar(canvas, length=100, orient=HORIZONTAL, mode='determinate') progress.place(relx=move_x+0.45, rely=0.38, relwidth=0.5, anchor='n') show_button = Button(canvas, text='Show Tweets', font='Helvetica 20 bold', command=lambda: show_tweets(saveFile_text.get(1.0, 'end'))) show_button.place(relx=move_x+0.3, rely=0.42, relwidth=0.15, relheight=0.05, anchor='n') reset_button = Button(canvas, text='Reset', font='Helvetica 20 bold', command=lambda: reset()) reset_button.place(relx=move_x+0.6, rely=0.42, relwidth=0.15, relheight=0.05, anchor='n') frame = Frame(canvas, bd=10, bg='#ececec') frame.config(highlightbackground="red", highlightcolor="red") model = TableModel() frame.place(relx=0.1, rely=0.5, relwidth=0.8, relheight=0.45) Table = TableCanvas(frame, model=model, cols=3, thefont=('Helvetica', 13), rows=Total_Tweets, rowheight=50, rowselectedcolor='#ececec', cellbackgr='#ececec', read_only=False) Table.show() #Table.place(relx=0.06, rely=0.06, relwidth=0.94, relheight=0.94) root.mainloop() if __name__ == "__main__": pass
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 = []
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 GraficInterfaceDb: def __init__(self, parent): self.listEnfermedad = ['a', "d", "c"] self.listMedicamentos = ['a', "d", "c"] self.listObserver = [] self.actualizarListas() self.actualrow = 0 self.rowEvent = 99 #Ventana de tablas y entradas self.r1 = parent self.r = Frame(self.r1) self.r1.wm_title("Ventana de busqueda") self.group = LabelFrame(self.r, bd=0) # self.group.grid(row=0,column=0,sticky=NW, padx=5, pady=5) self.group.pack(side=LEFT) self.r.pack(expand=True, fill='x', side=LEFT) # Ventana que muestra antecedesntes y informacion especifica de radiografia self.a = Frame(self.r1, padx=20, pady=20) self.b = VentanaDetalles(self.a) self.b.setWindow(self) self.a.pack(side=RIGHT) #Filtrar por id self.putInPlace(IdSearch) #Filtrar por nombre self.putInPlace(NameSearch) #Filtrar por apellido self.putInPlace(LastNameSearch) #Filtrar por Rut self.putInPlace(RutSearch) #Filtrar por sexo self.putInPlace(SexoSearch) #Filtrar por Enfermedad y confirmado comboBox self.listObserver.append(self.putInPlace(Enfermedadearch)) #Filtro confirmado self.putInPlace(ConfirmadoSearch) #Tipo de radiografia self.putInPlace(TipoRadioSearch) #Fecha inicio fecha final self.putInPlace(FechaSearch) #Fuma self.putInPlace(FumaSearch) #Medicamento self.listObserver.append(self.putInPlace(MedicamentoSearch)) #Mostrar resultados marco11 = Frame(self.r) bSearch = Button(marco11, text="Busqueda", command=self.doQuery) bSearch.pack(padx=5, pady=5) lResultados = Label(marco11, text="Resultados de query: ") lResultados.pack(padx=5, pady=5) # marco11.grid(row=self.actualrow, column=0,sticky=W, padx=5, pady=5) marco11.pack() self.actualrow += 1 marco12 = Frame(self.r) self.model = TableModel() self.table = TableCanvas(marco12, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial', 9), rowheight=18, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) self.table.createTableFrame() # marco12.grid(row=self.actualrow,column=0,sticky=W, padx=5, pady=5) marco12.pack(expand=False, fill='x') self.actualrow += 1 self.actualizarListas() self.r1.bind("<Button-1>", self.changeCurrentId) def getEnfList(self): print "Lista de enfermedad " + str(self.listEnfermedad) return self.listEnfermedad def getMedList(self): return self.listMedicamentos #Si quieres gridear creo que aqui es un buen lugar def putInPlace(self, claseBusqueda): #SI ACA COLOCAS TRUE TODOS LOS COMPONENTES NO HACEN PACK Y SE GUARDAN EN LISTA self.listaComponente #Puedes cambiar tanto el parent como el grid objetoNuevo = claseBusqueda(self.group, True) cont = 1 #Ejemplo de como se podrian sacar los componentes for comp in objetoNuevo.listaComponente: comp.grid(row=self.actualrow, column=cont) # comp.pack() cont += 1 listaSearch.append(objetoNuevo) self.actualrow += 1 return objetoNuevo def getCurrentIdRadio(self): try: print self.table.get_currentRecord() return self.table.get_currentRecord()[idColumnName] except: return None def actualizarListas(self): self.listEnfermedad = auxProcessList(queryListaEnf, "") self.listMedicamentos = auxProcessList(queryListaMed, "") for element in self.listObserver: element.update(self) def changeCurrentId(self, event): print "Antiguo ", self.rowEvent, " real ", self.table.currentrow if (self.rowEvent != self.table.currentrow): self.rowEvent = self.table.currentrow print("Evento activado") self.b.setValues(event) pass def doQuery(self): self.actualizarListas() print "Im about to query" resultSearch = [] for element in listaSearch: if (element.isActive()): result = element.giveFilterResults() print result if (len(resultSearch) != 0): set1 = set(result) set2 = set(resultSearch) set3 = set1 & set2 print set3 resultSearch = set3 else: resultSearch = result self.showResultInTable(resultSearch) return def showResultInTable(self, lista): data = {} resultQuery = [] #Ahora esta mostrando todas las radiografias que encuentra con criterios (incluso si no tieneen enf asociada) contador = 0 columnNames = {} if (len(lista) != 0): resultQuery = askDb(queryMostrar, (tuple(lista), )) resultQuery2 = askDb(metaquery, (tuple(lista), )) for index, name in enumerate(resultQuery2): columnNames[index] = name[0] for element in resultQuery: temp = zip(element, range(len(element))) tempDic = {} for atomicVal in temp: print atomicVal tempDic[str(columnNames[atomicVal[1]])] = str(atomicVal[0]) data[str(contador)] = tempDic contador += 1 self.model.setupModel({}) self.model.importDict(data) self.table.redrawTable() self.b.setValues(0) return
def create_table(self): self.table = TableCanvas(self.tframe, self.tmodel) self.table.createTableFrame() return
def adjustColumnWidths(self): self.cols = self.model.getColumnCount() TableCanvas.adjustColumnWidths(self)
import time import Tkinter from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel master = Tkinter.Tk() tframe = Tkinter.Frame(master) tframe.pack() table = TableCanvas(tframe) table.createTableFrame() # Create a model from data and init. model = TableModel() table = TableCanvas(tframe, model=model,width=1200, height=800) table.createTableFrame() raw_input('Redraw table and put data into it!') # Call to update after content change. table.redrawTable() #To import from a dictionary we get a handle on the model #(or we can create the model first and supply it as an argument to the table constructor): data = {'rec1': {'col1': 99.88, 'col2': 108.79, 'label': 'rec1'}, 'rec2': {'col1': 99.88, 'col2': 108.79, 'label': 'rec2'}, 'rec3': {'col1':1.0, 'label':'rec3'}, 'rec4': {'col1':2.0, 'label':'rec4'} } model = table.model model.importDict(data) #can import from a dictionary to populate model
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 __init__(self, parent=None, model=None, width=None, height=None, rows=10, cols=5, **kwargs): TableCanvas.__init__(self,parent,mTableModel(rows=rows,columns=cols) if not model else model, \ width,height,rows,cols,**kwargs) self.is_sorted = False
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 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('')
#!python2 #coding: utf-8 from Tkinter import * from ttk import * from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel ''' 创建Table ''' 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
root.geometry('1000x700') f = Figure(figsize=(4, 4), dpi=50) axis = f.add_subplot(111) canvas = FigureCanvasTkAgg(f, master=root) canvas.get_tk_widget().place(x=10, y=30) frame2 = Frame(root) frame2.place(x=20, y=300) X_Axis = pylab.arange(0, 100, 1) plotFigure = Figure(figsize=(4, 4), dpi=50) axis2 = plotFigure.add_subplot(111) axis2.grid(True) axis2.set_title("Mean value per Frame") axis2.axis([0, 100, 0, 255]) Plot = axis2.plot(X_Axis, [0] * 100, 'o-', color='r', markersize=6) model = TableModel() table = TableCanvas(frame2, model, height=100, width=300) model = table.model table.createTableFrame() canvas2 = FigureCanvasTkAgg(plotFigure, master=root) canvas2.get_tk_widget().place(x=500, y=30) b1 = Button(root, text="Start", bg='white', command=video_start).place(x=50, y=600) b2 = Button(root, text="Stop", bg='white', command=video_stop).place(x=400, y=600) root.mainloop() #===========================================================================================
class ManagerUI(object): def __init__(self, top_, manager_): self.top = top_ self.manager = manager_ self.initComponent() self.initTable() self.quitButton = Tkinter.Button(self.top, text = '退出', command = self.top.quit) self.quitButton.pack() def initComponent(self, ev = None): # 弄个列表来管理? # 注销、标签 entryWidth = 40 #这6个横着摆? self.ISBN = Tkinter.StringVar(self.top) self.ISBNEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.ISBN) self.ISBNEntry.bind('<Return>', self.getBook) self.ISBNEntry.pack() self.bookname = Tkinter.StringVar(self.top) self.booknameEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.bookname) self.booknameEntry.pack() self.authorname = Tkinter.StringVar(self.top) self.authornameEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.authorname) self.authornameEntry.pack() self.publisher = Tkinter.StringVar(self.top) self.publisherEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.publisher) self.publisherEntry.pack() self.publishtime = Tkinter.StringVar(self.top) self.publishtimeEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.publishtime) self.publishtimeEntry.pack() self.price = Tkinter.StringVar(self.top) self.priceEntry = Tkinter.Entry(self.top, width = entryWidth, textvariable = self.price) self.priceEntry.pack() self.bfm = Tkinter.Frame(self.top) # TODO: 按钮加图片(扁平化) self.addBookButton = Tkinter.Button(self.bfm, text = '添加', command = self.addBook) # 可选TODO:撤销刚刚进行的操作 self.getBookButton = Tkinter.Button(self.bfm, text = '获取', command = self.getBook) self.deleteButton = Tkinter.Button(self.bfm, text = '删除', command = self.deleteBook) self.clearTableButton = Tkinter.Button(self.bfm, text = '清空文本', command = self.clearTable) self.addBookButton.pack(side = Tkinter.LEFT) self.getBookButton.pack(side = Tkinter.LEFT) self.deleteButton.pack(side = Tkinter.LEFT) self.clearTableButton.pack(side = Tkinter.LEFT) self.bfm.pack() def initTable(self, ev = None): self.tableFrame = Tkinter.Frame(self.top) self.tableFrame.pack(expand = True, fill = Tkinter.BOTH) # 后期修改 self.top.geometry('920x700+200+100') self.model = TableModel(rows = 0, columns = 0) # like HTML self.bookTable = TableCanvas(self.tableFrame, self.model, cellwidth=120, cellbackgr='#e3f698', thefont=('Arial',12), rowheight=22, rowheaderwidth=30, rowselectedcolor='yellow', editable=False) # like CSS self.bookTable.createTableFrame() self.colnames = ('ISBN', '书名', '作者', '出版社', '出版时间', '价格') for name in self.colnames: self.bookTable.addColumn(name) self.bookTable.addRows(1) self.bookTable.autoResizeColumns() def addBook(self, ev = None): # TODO: 防止 SQL 注入 try: self.manager.query('insert into book values(%s,\'%s\',\'%s\',\'%s\',\'%s\',%s)' % (self.ISBN.get(), self.bookname.get().encode('utf8'), self.authorname.get().encode('utf8'), self.publisher.get().encode('utf8'), self.publishtime.get(), self.price.get())) self.manager.commit() except MySQLdb.IntegrityError, err: # TODO 已经存在此书 print u'已经存在此书'
from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel from Tkinter import * master = Tk() tframe = Frame(master) tframe.pack() model = TableModel() table = TableCanvas(tframe, model=model) #model = table.model #model.addColumn('col1') #model.addColumn('col2') #model.addColumn() data = { '1': { 'col1': 99.88, 'col2': 108.79 }, '2': { 'col1': 99.88, 'col2': 108.79 } } model.importDict(data) table.createTableFrame() #table.pack() master.mainloop()
def __init__(self,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)
class _StatisticDialog(TopDialog): def __init__(self, parent, factory, statistic, stat_count_row): TopDialog.__init__(self, parent, (statistic, stat_count_row)) self.factory = factory self.title(_("win_statistic_title")) self.wait_visibility() self.set_size(self.table_detailed_stat.get_totalWidth(), 750) self.resizable(True, True) self.grab_set() self.run() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [ row_name[i] + it for i, it in enumerate(statistic.get_common_stat()) ]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas( self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column( col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append( Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def init_window(self, (statistic, stat_count_row)): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en()
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)
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)
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)
import tkinter as tk from tkintertable.Tables import TableCanvas from tkintertable.TableModels import TableModel root = tk.Tk() tframe = tk.Frame(root) tframe.pack() table = TableCanvas(tframe) table.createTableFrame() root.mainloop()
class _StatisticDialog(TopDialog): def __init__(self, parent, factory, statistic, stat_count_row): TopDialog.__init__(self, parent, (statistic, stat_count_row)) self.factory = factory self.title(_("win_statistic_title")) self.wait_visibility() self.set_size(self.table_detailed_stat.get_totalWidth(), 750) self.resizable(True, True) self.grab_set() self.run() def init_common_stat(self, statistic): self.frame_common_stat = Frame(self) self.frame_common_stat.grid(row=1, column=0, sticky=N + S + E + W) model_common_stat = TableModel(10, False) model_common_stat.add_column(_("clm_name"), typedata='text', align='left') model_common_stat.add_column(_("clm_ru_en_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_en_ru_cnt"), typedata='number', align='right', max_val=u"99999") model_common_stat.add_column(_("clm_ru_en_perc"), typedata='percent', align='right', max_val=u"100.0 %") model_common_stat.add_column(_("clm_en_ru_perc"), typedata='percent', align='right', max_val=u"100.0 %") row_name = [[_("row_learned")], [_("row_study")], [_("row_learn")], [_("row_total")]] for row in [row_name[i] + it for i, it in enumerate(statistic.get_common_stat())]: model_common_stat.add_row(row) self.table_common_stat = TableCanvas(self.frame_common_stat, model_common_stat, sort_enable=False) self.table_common_stat.createTableFrame() self.frame_common_stat.grid_forget() def init_detailed_stat(self, statistic, stat_count_row): self.frame_detailed_stat = Frame(self) self.frame_detailed_stat.grid(row=1, column=0, sticky=N + S + E + W) self.model_ru_en = TableModel(stat_count_row, True) self.model_ru_en.add_column(_("clm_word"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_transcription"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_translate"), typedata='text', align='left') self.model_ru_en.add_column(_("clm_cnt_suc"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_cnt_err"), typedata='number', align='right', max_val=u"999") self.model_ru_en.add_column(_("clm_study_perсent"), typedata='percent', align='right', max_val=u"100.0 %") for row, word in statistic.get_ru_en(): self.model_ru_en.add_row(row, word) self.model_ru_en.sort(5, True) self.table_detailed_stat = TableCanvas(self.frame_detailed_stat, self.model_ru_en, sort_enable=True, callback=self.draw_callback, dbl_click_callback=self.rename_dlg) self.table_detailed_stat.createTableFrame() self.model_en_ru = TableModel(stat_count_row, True) self.model_en_ru.add_column(_("clm_word"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_transcription"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_translate"), typedata='text', align='left') self.model_en_ru.add_column(_("clm_cnt_suc"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_cnt_err"), typedata='number', align='right') self.model_en_ru.add_column(_("clm_study_perсent"), typedata='percent', align='right') for row, word in statistic.get_en_ru(): self.model_en_ru.add_row(row, word) self.model_en_ru.sort(5, True) for col in range(0, self.model_en_ru.get_column_count()): self.model_en_ru.get_column(col).width = self.model_ru_en.get_column(col).width def button_add(self, text, command): self.buttons.append(Button(self.frame_btn, text=text, command=command, borderwidth=2, default="normal")) ind = len(self.buttons) self.buttons[-1].grid(row=0, column=ind, sticky=N + S + E + W, pady=5, padx=3) def button_sel(self, cur_button): self.last_button = cur_button for i, it in enumerate(self.buttons): if i == cur_button: it.configure(relief="sunken") else: it.configure(relief="raised") self.update_idletasks() def init_window(self, (statistic, stat_count_row)): self.last_button = 0 self.buttons = [] self.frame_btn = Frame(self, borderwidth=2, relief=GROOVE) self.frame_btn.grid(row=0, column=0, sticky=N + S + E + W) Label(self.frame_btn, text="").grid(row=0, column=0) self.button_add(_("btn_ru_en"), self.show_ru_en) self.button_add(_("btn_en_ru"), self.show_en_ru) self.button_add(_("btn_common_stat"), self.show_common_stat) Label(self.frame_btn, text="").grid(row=0, column=4) self.frame_btn.grid_rowconfigure(0, weight=1) self.frame_btn.grid_columnconfigure(1, weight=1) self.frame_btn.grid_columnconfigure(2, weight=1) self.frame_btn.grid_columnconfigure(3, weight=1) self.init_common_stat(statistic) self.init_detailed_stat(statistic, stat_count_row) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1) self.button_sel(0) self.show_ru_en()