def show(frame, iterator): """Выводит на экран выборку, заданную в iterator""" scrollbar = Scrollbar(frame) tree = Treeview(frame, selectmode='none', padding=3, style='Custom.Treeview', height=REPORT_HEIGHT, yscrollcommand=scrollbar.set) tree.pack(side=LEFT, fill=BOTH, expand=YES) scrollbar.config(command=tree.yview) scrollbar.pack(side=LEFT, fill=Y) tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT)) tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT), background='#f5f5ff') Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2) columns = ['#' + str(x + 1) for x in range(8)] tree.configure(columns=columns) for q in range(len(header)): tree.heading('#%d' % (q + 1), text=header[q], anchor='w') tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1], anchor='w') tree.heading('#0', text='', anchor='w') tree.column('#0', width=0, anchor='w', minwidth=0) flag = True summ = 0 for item in iterator: value = item.quantity * item.price * (100 - item.discount) / 100 summ += value col = [] col.append(add_s(item.check.id)) col.append(add_s(item.goods.cathegory.name)) col.append(add_s(item.goods.name)) col.append(add_s(item.quantity)) col.append(add_s(item.discount) +'%' if item.discount else ' -- ') col.append(add_s(u'%6.2f грн.' % value)) col.append(add_s(item.check.date_time.strftime('%d.%m.%Y'))) col.append(add_s(item.check.date_time.time())[:8]) flag = not flag if flag: tree.insert('', 'end', text='', values=col, tag='2') else: tree.insert('', 'end', text='', values=col, tag='1') return summ
def initUI(self): self.entries_found = [] self.parent.title("Search your command cards") self.style = Style() self.style.theme_use("default") self.pack() self.input_title = Label(self, text="Enter your command below") self.input_title.grid(row=0, columnspan=2) self.input_box = Entry(self, width=90) self.input_box.grid(row=1, column=0) self.input_box.focus() self.input_box.bind("<Key>", self.onUpdateSearch) self.search_btn = Button(self, text="Search", command=self.onSearch) self.search_btn.grid(row=1, column=1) self.output_box = Treeview(self, columns=("Example")) ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview) xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview) self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set) self.output_box.heading('Example', text='Example', anchor='w') self.output_box.column("#0", minwidth=0, width=0, stretch=NO) self.output_box.column("Example", minwidth=0, width=785) self.output_box.bind("<Button-1>", self.OnEntryClick) self.output_box.grid(row=3, columnspan=2) self.selected_box = Text(self, width=110, height=19) self.selected_box.grid(row=4, columnspan=2) self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd) self.gotoadd_btn.grid(row=5)
def selection_set(self, node): """Node names on the breakpoint tree are the filename. On Windows, this requires escaping, because backslashes in filenames cause problems with Tk. """ Treeview.selection_set(self, self._nodify(node))
def __init__(self, *args, **kwargs): # Only a single stack frame can be selected at a time. kwargs['selectmode'] = 'browse' Treeview.__init__(self, *args, **kwargs) self.locals = self.insert( '', 'end', ':builtins:', text='builtins', open=False, ) self.globals = self.insert( '', 'end', ':globals:', text='globals', open=False, ) self.locals = self.insert( '', 'end', ':locals:', text='locals', open=True, ) self['columns'] = ('value',) self.column('#0', width=150, anchor='w') self.column('value', width=200, anchor='w') self.heading('#0', text='Name') self.heading('value', text='Value')
def __init__(self, parent): Frame.__init__(self, parent) self.tree = Treeview(self) self.tree["columns"] = ("item1", "item2") self.tree.heading("item1", text="Column 1") self.tree.heading("item2", text="Column 2") self.tree.insert("", 0, text="Item 1", values=("Value 1", "Value 2")) row2 = self.tree.insert("", 1, "row2", text="Item 2") self.tree.insert(row2, "end", "item1", text="Item 1", values=("3", "7")) self.tree.insert(row2, "end", "item2", text="Item 2", values=("2", "5")) self.tree.pack(expand=1, fill="both") self.delete = Button(self, text="Delete Row", command=self.on_delete) self.delete.pack(side="bottom")
def left_side(self, master): self.nombre = Entry(master, justify=CENTER, bd=3, font=('Ravie', 11), textvariable=self.NameVar) self.nombre.pack(side=TOP, fill=X) self.nombre.bind("<Key>", self.Enter) self.texto = Entry(master, justify=CENTER, bd=3, font=('Ravie', 11), textvariable=self.TextVar) self.texto.pack(side=TOP, fill=X) self.texto.bind("<Key>", self.Enter) self.tag = Entry(master, justify=CENTER, bd=3, font=('Ravie', 11), textvariable=self.TagsVar) self.tag.pack(side=TOP, fill=X) self.tag.bind("<Key>", self.Enter) self.tree = Treeview(master) self.tree.pack(side=LEFT, expand=YES, fill=BOTH) self.tree.bind("<Double-1>", self.OnDoubleClick)
def create_file_treeview(self): self.fileTreeView = Treeview(self.main_window) self.fileTreeYScrollbar = Scrollbar(self.main_window, orient='vertical', command=self.fileTreeView.yview) self.fileTreeXScrollbar = Scrollbar(self.main_window, orient='horizontal', command=self.fileTreeView.xview) self.fileTreeView.configure(yscroll=self.fileTreeYScrollbar.set, xscroll=self.fileTreeXScrollbar.set) self.fileTreeView.grid(row=self.fileTreeRow, column=self.fileTreeCol, sticky=NS, rowspan=3) self.fileTreeYScrollbar.grid(row=self.fileTreeRow, column=self.fileTreeScrollbarCol, sticky=NS, rowspan=3) self.fileTreeXScrollbar.grid(row=self.horizontalScrollbarRow, column=self.fileTreeCol, sticky=EW) self.fileTreeView.tag_configure('red', background=self.redColor) self.fileTreeView.tag_configure('green', background=self.greenColor) self.fileTreeView.tag_configure('yellow', background=self.yellowColor) self.fileTreeView.tag_configure('purpleLight', background=self.purpleLight) # hide it until needed self.fileTreeView.grid_remove() self.fileTreeYScrollbar.grid_remove() self.fileTreeXScrollbar.grid_remove()
def __draw_scores(self): self.score_list = Treeview(self, columns=('name', 'score')) self.score_list['show'] = 'headings' self.score_list.heading('name', text='Name') self.score_list.column('name', width=80, anchor=CENTER) self.score_list.heading('score', text='Score') self.score_list.column('score', width=80, anchor=CENTER) self.score_list.grid(row=1, column=1, padx=(0, 20))
def __init__(self, gesture, master=None, yscrollcommand=None): self.gesture = gesture Treeview.__init__(self, master=master, columns=self.generate_columns(), yscrollcommand=yscrollcommand) self.setup_column_headers() self.populate_list() self.pack(fill="both", expand="yes")
def __init__(self, parent, model): Treeview.__init__(self, parent, columns=["COL0", "COL1"], selectmode="browse") self.heading(0, text="Number") self.heading(1, text="Text") self["show"] = "headings" self.counter = 0 self.bind("<<TreeviewSelect>>", self.on_select) self.model = model self.model.add_listener(self.on_model)
def __init__(self, *args, **kwargs): # Only a single stack frame can be selected at a time. kwargs['selectmode'] = 'browse' self.normalizer = kwargs.pop('normalizer') Treeview.__init__(self, *args, **kwargs) self['columns'] = ('line',) self.column('line', width=50, anchor='center') self.heading('#0', text='File') self.heading('line', text='Line')
def __init__(self, parent, timeEntries): columns = ("project", "start", "stop", "duration") Treeview.__init__(self, parent, columns=columns) for col in columns: self.heading(col, text=col, command=lambda: self.sort_column(col, False)) [self.insertTimeEntry(e) for e in timeEntries.values()] self.sort_column("start", True)
def initComponents(self): """ GUI components initialization """ self.buttons = {} frame1 = Frame(self) frame1.place(relx=0.01, rely=0.03, width=600, height=30) self.accountLabel = Label(frame1, text='accStatus') self.accountLabel.place(x=0, width=80, height=30) self.buttons['logout'] = Button (frame1, text="Logout") self.buttons['logout'].place(x=85, height=24, width=80) self.buttons['about'] = Button (frame1, text="About") self.buttons['about'].place(x=170, height=24, width=80) frame2 = Frame(self) frame2.place(relx=0.01, rely=0.1, width=600, height=30) self.buttons['new'] = Button (frame2, text="New") self.buttons['new'].place(x=0, height=24, width=80) self.buttons['edit'] = Button (frame2, text="Edit") self.buttons['edit'].place(x=85, height=24, width=80) self.buttons['delete'] = Button (frame2, text="Delete") self.buttons['delete'].place(x=170, height=24, width=80) self.buttons['find'] = Button (frame2, text="Find") self.buttons['find'].place(x=255, height=24, width=80) frame3 = Frame(self) frame3.place(relx=0.01, rely=0.93, width=600, height=30) self.buttons['prev'] = Button (frame3, text="Prev") self.buttons['prev'].place(x=0, y=0, height=27, width=67) self.pageLabel = Label(frame3, text='pageStatus') self.pageLabel.place(x=85, width=80, height=30) self.buttons['next'] = Button (frame3, text="Next") self.buttons['next'].place(x=170, y=0, height=27, width=67) self.frame = Frame (self) self.frame.place(relx=0.01, rely=0.16, relheight=0.75, relwidth=0.98) self.frame.configure(relief=GROOVE) self.frame.configure(borderwidth="2") self.frame.configure(relief="groove") self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) container = self.frame tree = Treeview(container, columns=self.tree_columns, show="headings", selectmode='browse') self.tree = tree hsb = Scrollbar(container, orient="horizontal", command=self.tree.xview) self.tree.configure(xscrollcommand=hsb.set) # self.tree.grid(column=0, row=0, sticky='nsew', in_=container) self.tree.pack() hsb.grid(column=0, row=1, sticky='ew') container.grid_columnconfigure(0, weight=1) container.grid_rowconfigure(0, weight=1) tree.grid(column=0, row=0, sticky='nsew') for col in self.tree_columns: self.tree.heading(col, text=col.title())
def __init__(self, master, headers, data, name=None): Frame.__init__(self, master, name=name) #: column headers self.headers = headers #: table data self.data = data #: :class:`~ttk.Treeview` that only shows "headings" not "tree columns" self.tree = Treeview(self, columns=self.headers, show="headings", name='tabletree') #: vertical scrollbar self.yscroll = Scrollbar(self, orient="vertical", command=self.tree.yview, name='table_yscroll') #: horizontal scrollbar self.xscroll = Scrollbar(self, orient="horizontal", command=self.tree.xview, name='table_xscroll') self.tree['yscrollcommand'] = self.yscroll.set # bind to scrollbars self.tree['xscrollcommand'] = self.xscroll.set # position widgets and set resize behavior self.tree.grid(column=0, row=0, sticky=(N + E + W + S)) self.yscroll.grid(column=1, row=0, sticky=(N + S)) self.xscroll.grid(column=0, row=1, sticky=(E + W)) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) # build tree for col in self.headers: # NOTE: Use col as column identifiers, crafty! # NOTE: Also change col to title case using str.title() # NOTE: make lambda behave nicely in a loop using default arg! callback = lambda c=col: self.sortby(c, False) self.tree.heading(col, text=col.title(), command=callback) # adjust the column's width to the header string self.tree.column(col, width=tkFont.Font().measure(col.title())) # insert a new top-level treeview item by suing an empty string for item in self.data: self.tree.insert('', END, values=item) # adjust column's width if necessary to fit each value for idx, val in enumerate(item): col_width = tkFont.Font().measure(val) # option can be specified at least 3 ways: as (a) width=None, # (b) option='width' or (c) 'width', where 'width' can be any # valid column option. if self.tree.column(self.headers[idx], 'width') < col_width: self.tree.column(self.headers[idx], width=col_width)
def __init__(self, *args, **kwargs): # Only a single stack frame can be selected at a time. kwargs['selectmode'] = 'browse' self.normalizer = kwargs.pop('normalizer') Treeview.__init__(self, *args, **kwargs) # self['columns'] = ('line',) # self.column('line', width=100, anchor='center') self.heading('#0', text='File') # self.heading('line', text='Line') # Set up styles for line numbers self.tag_configure('enabled', foreground='red') self.tag_configure('disabled', foreground='gray') self.tag_configure('ignored', foreground='green') self.tag_configure('temporary', foreground='pink')
def _create_treeview(self, parent): f = Frame(parent) #f.pack(side=TOP, fill=BOTH, expand=Y) f.grid(row=0, column=0, sticky=NSEW, columnspan=3) # create the tree and scrollbars self.dataCols = ('fullpath', 'type', 'status') self.tree = Treeview(columns=self.dataCols, displaycolumns='status') ysb = Scrollbar(orient=VERTICAL, command= self.tree.yview) xsb = Scrollbar(orient=HORIZONTAL, command= self.tree.xview) self.tree['yscroll'] = ysb.set self.tree['xscroll'] = xsb.set # setup column headings self.tree.heading('#0', text='Directory Structure', anchor=W) self.tree.heading('status', text='Status', anchor=W) self.tree.column('status', stretch=0, width=100) # add tree and scrollbars to frame self.tree.grid(in_=f, row=0, column=0, sticky=NSEW) ysb.grid(in_=f, row=0, column=1, sticky=NS) xsb.grid(in_=f, row=1, column=0, sticky=EW) # set frame resizing priorities f.rowconfigure(0, weight=1) f.columnconfigure(0, weight=1) # action to perform when a node is expanded self.tree.bind('<<TreeviewOpen>>', self._update_tree) self.tree.bind("<Double-1>", self.OnDoubleClick)
def initUI(self): self.entries_found = [] self.parent.title("Search your command cards") self.style = Style() self.style.theme_use("default") self.pack() self.input_title = Label(self, text="Enter your command below") self.input_title.grid(row=0, columnspan=2) self.input_box = Entry(self, width=90) self.input_box.grid(row=1, column=0) self.input_box.focus() self.input_box.bind("<Key>", self.onUpdateSearch) self.search_btn = Button(self, text="Search", command=self.onSearch) self.search_btn.grid(row=1, column=1) self.output_box = Treeview(self, columns=("Example")) ysb = Scrollbar(self, orient='vertical', command=self.output_box.yview) xsb = Scrollbar(self, orient='horizontal', command=self.output_box.xview) self.output_box.configure(yscroll=ysb.set, xscroll=xsb.set) self.output_box.heading('Example', text='Example', anchor='w') self.output_box.column("#0",minwidth=0,width=0, stretch=NO) self.output_box.column("Example",minwidth=0,width=785) self.output_box.bind("<Button-1>", self.OnEntryClick) self.output_box.grid(row=3, columnspan=2) self.selected_box = Text(self, width=110, height=19) self.selected_box.grid(row=4, columnspan=2) self.gotoadd_btn = Button(self, text="Go to Add", command=self.onGoToAdd) self.gotoadd_btn.grid(row=5)
def __init__(self, controller): self.controller = controller self.currIndex = 0 # initialize the GUI self.app = Tk() self.app.title('Jack Magee\'s Pub') self.tree = Treeview(self.app, height=30) # name the tree columns, not sure if they have to be named numbers but that's how the example did it self.tree["columns"]=("one", "two", "three", "four") # set the column widths self.tree.column("one", width=200) self.tree.column("two", width=300) self.tree.column("three", width=200) self.tree.column("four", width=200) # set the column headings self.tree.heading("#0", text= "ID") self.tree.heading("one", text="Name") self.tree.heading("two", text="Order") self.tree.heading("three", text="Price") self.tree.heading("four", text="Respond (double-click)") self.tree.pack() # register handler for double-clicks self.tree.bind("<Double-1>", self.OnDoubleClick)
def createQSOView(self, master): self.qsoviewScrollbar = Scrollbar(master) self.qsoview = Treeview(master, show=('headings'), yscrollcommand=self.qsoviewScrollbar.set) self.qsoviewfields = {'day': {'name': "D", 'width': 10}, 'month': {'name': "M", 'width': 10}, 'year': {'name': "Y", 'width': 20}, 'timeon': {'name': "Time", 'width': 30}, 'timeoff': {'name': "Timeoff", 'width': 30}, 'band': {'name': "Band", 'width': 20}, 'freq': {'name': "Frequency", 'width': 50}, 'mode': {'name': "Mode", 'width': 25}, 'call': {'name': "Call", 'width': 50}, 'srst': {'name': "S RST", 'width': 25}, 'rrst': {'name': "R RST",'width': 25}, 'name': {'name': "Name",'width': 40}, 'grid': {'name': "Gridsquare",'width': 30}, 'iota': {'name': "IOTA", 'width': 30}, 'qsls': {'name': "Q S",'width': 25}, 'qsls_date': {'name': "Q S D",'width': 50}, 'qslr': {'name': "Q R",'width': 25}, 'qslr_date': {'name': "Q R D",'width': 50}, 'lotw_qsls': {'name': "LQ S",'width': 25}, 'lotw_qsls_date': {'name': "LQ S D",'width': 50}, 'lotw_qslr': {'name': "LQ R",'width': 25}, 'lotw_qslr_date': {'name': "LQ R D",'width': 50}} self.qsoviewdisplayesfields = ('day', 'month', 'year', 'timeon', 'band', 'freq', 'mode', 'call', 'srst', 'rrst', 'name', 'grid', 'iota', 'qsls', 'qsls_date', 'qslr', 'qslr_date', 'lotw_qsls', 'lotw_qsls_date', 'lotw_qslr', 'lotw_qslr_date') self.qsoview["columns"] = self.qsoviewfields.keys() self.qsoview["displaycolumns"] = self.qsoviewdisplayesfields self.qsoview.column(0, width=40) for columnname, data in self.qsoviewfields.items(): # set columnwidth for QSOView self.qsoview.column(columnname, width=data['width']) # set QSOView headers self.qsoview.heading(columnname, text=data['name']) for i in range(400): self.qsoview.insert('', 'end', str(i), values=(str(i), 'bar'+str(i))) self.qsoviewScrollbar.config(command=self.qsoview.yview) self.qsoviewScrollbar.grid(column=1, row=0, sticky=(N,S)) self.qsoview.grid(column=0, row=0, sticky=(N,S,E,W)) master.columnconfigure(0, weight=1) master.rowconfigure(0, weight=1)
def fill(self): super(self.__class__, self).fill() #Basisvelden self.identry = EntryField(self.veldenFrame, 'Projectnummer', row=0) self.naamentry = EntryField(self.veldenFrame, 'Projectnaam', row=1) self.jaarentry = EntryField(self.veldenFrame, 'Jaar', row=2) self.budgetentry = EntryField(self.veldenFrame, 'Budget', row=3) self.keywordLabel = Label(self.veldenFrame, text='Trefwoorden:') self.keywordLabel.grid(row=4, column=0, sticky=W) self.keywordText = Text(self.veldenFrame, relief=SUNKEN, wrap=WORD, width=60, height=3) self.keywordText.grid(row=4, column=1, sticky=W) #Partners self.partnersLabel = Label(self.veldenFrame, text='Relaties:') self.partnersLabel.grid(row=5, column=0) self.partnersFrame = Frame(self.veldenFrame) self.partnersFrame.grid(row=5, column=1, sticky=W+E) self.partnersListBox = Treeview(self.partnersFrame, columns=('Relatie', 'Rol'), height=3, show='headings', selectmode=BROWSE) self.partnersListBox.grid(row=0, column=0, sticky=W+E) self.partnersKnopFrame = Frame(self.veldenFrame) self.partnersKnopFrame.grid(row=6, column=1, sticky=E) self.pScrollbar = Scrollbar(self.partnersFrame) self.pScrollbar.grid(row=0, column=1, sticky=N+S+E) self.partnersListBox.config(yscrollcommand=self.pScrollbar.set) self.pScrollbar.config(command=self.partnersListBox.yview) self.partnersToevoegenKnop = Button(self.partnersKnopFrame, text='Toevoegen...', command=self.partnerToevoegen) self.partnersToevoegenKnop.grid() self.partnersVerwijderenKnop = Button (self.partnersKnopFrame, text='Verwijderen', command=self.partnerVerwijderen) self.partnersVerwijderenKnop.grid(row=0, column=1) self.partnersListBox.bind('<<TreeviewSelect>>', self.nieuwePartnerSelectie) #Bestanden self.bestandenHoofdFrame = Frame(self.resultaatframe) self.bestandenHoofdFrame.grid(row=2) self.bestandenLabel = Label(self.bestandenHoofdFrame, text='Bestanden:') self.bestandenLabel.grid(row=7, column=0, sticky=W) self.bestandenFrame = Frame(self.bestandenHoofdFrame) self.bestandenFrame.grid(row=7, column=1, sticky=W+E) self.bestandenListBox = Listbox(self.bestandenFrame, selectmode=EXTENDED, width=50, height=10) self.bestandenListBox.grid(row=0, column=0, sticky=W+E) self.bScrollbar = Scrollbar(self.bestandenFrame) self.bScrollbar.grid(row=0, column=1, sticky=N+S+E) self.bestandenListBox.config(yscrollcommand=self.bScrollbar.set) self.bScrollbar.config(command=self.bestandenListBox.yview) self.bestandenKnopFrame = Frame(self.bestandenHoofdFrame) self.bestandenKnopFrame.grid(row=8, column=1, sticky=E) self.bestandenToevoegKnop = Button(self.bestandenKnopFrame, text='Bestanden toevoegen...', command=self.bestandenToevoegen) self.bestandenToevoegKnop.grid(row=0, column=0, sticky=E) self.mapToevoegenKnop = Button(self.bestandenKnopFrame, text='Map toevoegen...', command=self.mapToevoegen) self.mapToevoegenKnop.grid(row=0, column=1, sticky=E) self.bestandenOphaalKnop = Button(self.bestandenKnopFrame, text='Ophalen...', command=self.bestandenOphalen) self.bestandenOphaalKnop.grid(row=0, column=2, sticky=E) self.bestandenVerwijderKnop = Button(self.bestandenKnopFrame, text='Verwijderen', command=self.bestandenVerwijderen) self.bestandenVerwijderKnop.grid(row=0, column=3, sticky=E) self.pollBestandenLijst() self.curid=-1
def __init__(self, root, frame, num, logit, all_values, list_styles_names): Treeview.__init__(self, root) self.root = root self.num = num self.frame = frame self.name = "MOXA-%s" % str(self.num) self.tree = Treeview(frame, style=list_styles_names[num]) self.tree["columns"] = ("one", "two", "three") self.tree.heading("#0", text="") self.tree.column("#0", minwidth=0, width=5, stretch=NO) self.tree.heading("one", text="Port") self.tree.column("one", minwidth=0, width=30, stretch=NO) self.tree.column("two", minwidth=0, width=name_column, stretch=NO) self.tree.heading("three", text="State") self.tree.column("three", minwidth=0, width=state_column, stretch=YES) self.tree['height'] = 32 self.tree.tag_configure('green', background='gray7', foreground='green2') self.tree.tag_configure('red', background='gray7', foreground='tomato2') self.tree.tag_configure('blue', background='gray7', foreground='RoyalBlue') self.tree.tag_configure('yellow', background='gray7', foreground='yellow') self.tree.tag_configure('ready', background='gray7', foreground='white') self.tree.tag_configure( 'focus', background='yellow', ) self.tree.bind("<Motion>", self.mycallback) self.last_focus = None self.tree.pack(side=LEFT) self.logit = logit self.moxa = all_values[self.num][0] self.wraplength = 180 for key in self.moxa.keys(): self.tree.insert("", "end", values=(str(key), self.moxa[key], "<><><>"), tags=("green", ))
def __init__(self, data, master=None): Treeview.__init__(self, master=master, columns=["friendly_name", "status"]) self.data = data self.heading("#0", text="Port", anchor="w") self.column("#0", width = 150) self.heading("friendly_name", text="Name", anchor="w") self.column("friendly_name", width = 250) self.heading("status", text="Status", anchor="w") self.column("status", width = 100) self.bind("<<TreeviewSelect>>", self.update_status_button) midi.init() self.populate_list() self.pack(fill="both", expand="yes")
def initUI(self): self.columnconfigure(0, weight=0) self.columnconfigure(1, weight=0) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=1) self.rowconfigure(0, weight=1) self.commandFrame = Frame(self, background="white") self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W+E) self.commandFrame.columnconfigure(1, weight=1) self.btnCommand = Button(self.commandFrame, text="Run") self.btnCommand.grid(row=0, column=0) self.strCommand = StringVar() self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand) self.entCommand.grid(row=0, column=1, sticky=W+E) self.lstMacro = Listbox(self) self.lstMacro.grid(row=1, column=0, sticky=N+S+W+E) self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse") self.treeview.grid(row=1, column=1, columnspan=4, sticky=N+S+W+E) self.treeScrollbar = Scrollbar(self) self.treeScrollbar.grid(row=1, column=5, sticky=N+S) self.treeview.config(yscrollcommand=self.treeScrollbar.set) self.treeScrollbar.config(command=self.treeview.yview) self.btnFrame = Frame(self, background="white") self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W+E) self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro) self.btnRun.grid(row=0, column=0) self.btnStop = Button(self.btnFrame, text="Stop") self.btnStop.grid(row=0, column=1) self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro) self.btnSaveMacro.grid(row=0, column=2) self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro") self.btnDeleteMacro.grid(row=0, column=3) self.btnDeleteState = Button(self.btnFrame, text="Delete State") self.btnDeleteState.grid(row=0, column=4)
def modelConfigFrame(self, parent): """ Create and place next under parent a frame containing the current model configuration. """ #Create container frame = Frame(parent) #Create treeView for model configuration self.modelTree = Treeview(parent, columns=('size', 'modified')) self.populateModelTree() self.modelTree.grid(row=1) #Bind right-click (<Button-3>) on tree items for contextual menus def treeContextualMenu(event): itemId = self.modelTree.identify_row(event.y) if itemId: self.modelTree.selection_set(itemId) item = self.modelTree.selection() ctxMenu = Menu(self.window, tearoff=0) ctxMenu.add_separator() if item[0][:4] == "tag:": tag = item[0][4:] ctxMenu.add_command( label="Add samples (from a csv file)", command=lambda: self.addSampleFileToModelDir(tag)) ctxMenu.add_separator() ctxMenu.add_command( label="Visualize feature map w.r.t loaded model", command=lambda: self.testOnLoadedModel( join(configs["model_data_dir"], tag), True)) elif item[0][:5] == "file:": filename = item[0][5:] ctxMenu.add_command( label="Test on loaded model", command=lambda: self.testOnLoadedModel( join(configs["model_data_dir"], filename), False)) ctxMenu.add_separator() ctxMenu.add_command( label="Delete", command=lambda: self.deleteModelFile(filename)) ctxMenu.add_separator() ctxMenu.tk_popup(event.x_root, event.y_root) self.modelTree.bind("<Button-3>", treeContextualMenu) return frame
def createui(self): image = Image.open('header.png') photo = ImageTk.PhotoImage(image) lbl = Label(self, image=photo) lbl.image = photo lbl.grid(row=0, column=0, columnspan=2, sticky='ns') self.treeview = Treeview(self) self.treeview['columns'] = ['title'] self.treeview.heading("#0", text='Repeticiones', anchor='center') self.treeview.column("#0", anchor="center", width=90) self.treeview.heading('title', text='Titulo', anchor='w') self.treeview.column('title', anchor='w', width=700) self.treeview.grid(sticky=(N, S, W, E)) self.treeview.bind("<Double-1>", self.openlink) ysb = Scrollbar(self, width=18, orient='vertical', command=self.treeview.yview) ysb.grid(row=1, column=1, sticky='ns') self.treeview.configure(yscroll=ysb.set) self.grid_rowconfigure(1, weight=1) self.grid_columnconfigure(0, weight=1)
def left_side(self, master): self.nombre = Entry(master, justify = CENTER, bd = 3, font = ('Ravie', 11), textvariable = self.NameVar) self.nombre.pack(side = TOP, fill = X) self.nombre.bind("<Key>", self.Enter) self.texto = Entry(master, justify = CENTER, bd = 3, font = ('Ravie', 11), textvariable = self.TextVar) self.texto.pack(side = TOP, fill = X) self.texto.bind("<Key>", self.Enter) self.tag = Entry(master, justify = CENTER, bd = 3, font = ('Ravie', 11), textvariable = self.TagsVar) self.tag.pack(side = TOP, fill = X) self.tag.bind("<Key>", self.Enter) self.tree = Treeview(master) self.tree.pack(side = LEFT, expand = YES, fill = BOTH) self.tree.bind("<Double-1>", self.OnDoubleClick)
def __init__(self, master, xml=None, heading_text=None, heading_anchor=None, padding=None, cursor=None, takefocus=None, style=None): Frame.__init__(self, master, class_="XML_Viwer") self._vsb = Scrollbar(self, orient=VERTICAL) self._hsb = Scrollbar(self, orient=HORIZONTAL) kwargs = {} kwargs["yscrollcommand"] = lambda f, l: autoscroll(self._vsb, f, l) kwargs["xscrollcommand"] = lambda f, l: autoscroll(self._hsb, f, l) if style is not None: kwargs["style"] = style if padding is not None: kwargs["padding"] = padding if cursor is not None: kwargs["cursor"] = cursor if takefocus is not None: kwargs["takefocus"] = takefocus self._treeview = Treeview(self, **kwargs) if heading_text is not None: if heading_anchor is not None: self._treeview.heading("#0", text=heading_text, anchor=heading_anchor) else: self._treeview.heading("#0", text=heading_text) self._treeview.bind("<<TreeviewOpen>>", self._on_open) self._treeview.bind("<<TreeviewClose>>", self._on_close) # Without this line, horizontal scrolling doesn't work properly. self._treeview.column("#0", stretch= False) self._vsb['command'] = self._treeview.yview self._hsb['command'] = self._treeview.xview self._treeview.grid(column=0, row=0, sticky=N+S+W+E) self._vsb.grid(column=1, row=0, sticky=N+S) self._hsb.grid(column=0, row=1, sticky=E+W) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._element_tree = None self._item_ID_to_element = {} if xml is not None: self.parse_xml(xml)
def __initUI(self): """ Initialize UI with a list and required entry fields and submit buttons.""" self.parent.title('Multiplayer Game') self.pack(fill=BOTH, expand=1) self.lobby_list = Treeview(self, columns=('room', 'players')) self.lobby_list['show'] = 'headings' self.lobby_list.heading('room', text='Room ID') self.lobby_list.column('room', width=250, anchor=CENTER) self.lobby_list.heading('players', text='Players') self.lobby_list.column('players', width=100, anchor=CENTER) self.lobby_list.grid(row=1, column=0, columnspan=2, rowspan=2, padx=20, pady=(10, 0)) self.connect_lobby = Button(self, text='Joining Sudoku\n Solving Session', command=self.__connect_lobby) self.connect_lobby.grid(row=3, column=1, pady=(0, 10)) Label(self, text='Creating new Sudoku\n solving session:').grid(row=4, column=0) self.max_players = Entry(self) self.max_players.grid(row=4, column=1) self.create_game = Button(self, text='Join new game', command=self.__create_game) self.create_game.grid(row=5, column=1)
def initUI(self): self.columnconfigure(0, weight=0) self.columnconfigure(1, weight=0) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=1) self.rowconfigure(0, weight=1) self.commandFrame = Frame(self, background="white") self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W + E) self.commandFrame.columnconfigure(1, weight=1) self.btnCommand = Button(self.commandFrame, text="Run") self.btnCommand.grid(row=0, column=0) self.strCommand = StringVar() self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand) self.entCommand.grid(row=0, column=1, sticky=W + E) self.lstMacro = Listbox(self) self.lstMacro.grid(row=1, column=0, sticky=N + S + W + E) self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse") self.treeview.grid(row=1, column=1, columnspan=4, sticky=N + S + W + E) self.treeScrollbar = Scrollbar(self) self.treeScrollbar.grid(row=1, column=5, sticky=N + S) self.treeview.config(yscrollcommand=self.treeScrollbar.set) self.treeScrollbar.config(command=self.treeview.yview) self.btnFrame = Frame(self, background="white") self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W + E) self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro) self.btnRun.grid(row=0, column=0) self.btnStop = Button(self.btnFrame, text="Stop") self.btnStop.grid(row=0, column=1) self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro) self.btnSaveMacro.grid(row=0, column=2) self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro") self.btnDeleteMacro.grid(row=0, column=3) self.btnDeleteState = Button(self.btnFrame, text="Delete State") self.btnDeleteState.grid(row=0, column=4)
def create_file_treeview(self): self.fileTreeView = Treeview(self.main_window) self.fileTreeYScrollbar = Scrollbar(self.main_window, orient='vertical', command=self.fileTreeView.yview) self.fileTreeXScrollbar = Scrollbar(self.main_window, orient='horizontal', command=self.fileTreeView.xview) self.fileTreeView.configure(yscroll=self.fileTreeYScrollbar.set, xscroll=self.fileTreeXScrollbar.set) self.fileTreeView.grid(row=self.fileTreeRow, column=self.fileTreeCol, sticky=NS, rowspan=3) self.fileTreeYScrollbar.grid(row=self.fileTreeRow, column=self.fileTreeScrollbarCol, sticky=NS, rowspan=3) self.fileTreeXScrollbar.grid(row=self.horizontalScrollbarRow, column=self.fileTreeCol, sticky=EW) self.fileTreeView.tag_configure('red', background=self.redColor) self.fileTreeView.tag_configure('green', background=self.greenColor) self.fileTreeView.tag_configure('yellow', background=self.yellowColor) # hide it until needed self.fileTreeView.grid_remove() self.fileTreeYScrollbar.grid_remove() self.fileTreeXScrollbar.grid_remove()
def __init__(self, app, printer, settings, logger, *arg): self.app = app self.printer = printer self.settings = settings self.logger = logger layers = self.app.gcodeInfo.layerOrder usage = self.app.gcodeInfo.filLayers self.selection = None Toplevel.__init__(self, app, *arg) self.title("Layer by Layer Filament Usage") self.protocol("WM_DELETE_WINDOW", self.doCancel) f = Frame(self) f.grid(row=1, column=1, rowspan=1, padx=10) self.tree = Treeview(self, height=12, selectmode='browse') self.sb = Scrollbar(self) self.sb.config(command=self.tree.yview) self.tree.config(yscrollcommand=self.sb.set) ln = [] for l in layerinfo: ln.append(l[0]) del ln[0] self.tree.config(columns=ln) for l in layerinfo: self.tree.column(l[0], width=l[1], anchor=l[2]) self.tree.heading(l[0], text=l[3]) self.sb.pack(side=RIGHT, fill=Y) self.tree.pack(side=LEFT, fill=BOTH, expand=1) prev = 0.0 tl = layers[-1] total = usage[tl] for l in layers: n = usage[l] self.tree.insert('', 'end', text=l, values=("%7.3f" % (n-prev), "%9.3f" % n, "%9.3f" % (total-n))) prev = n
def createWidgets(self): """Create all the initial widgets for this menu""" """Labels""" lbl = Label(self, text="Select test below", justify=LEFT) lbl.grid(row=self.TEXT_ROW, column=self.TEST_COL) """Tests""" self.trv = Treeview(self, columns=("Status"), displaycolumns='#all') for test in self.tests: treeviewInsertTest(self.trv, test) self.trv.column('#0', width=100) self.trv.heading('#0', text="Test") self.trv.heading('Status', text='Status') self.trv.grid(column=self.TEST_COL, row=self.TREEVIEW_ROW, columnspan=2) """Buttons""" self.btnOK = Button(self, text="OK", command=self.launchTest) self.btnOK.grid(row=self.BUTTON_ROW, column=0) self.btnQuit = Button(self, text="Quit", command=self.quit) self.btnQuit.grid(row=self.BUTTON_ROW, column=1)
def __init__(self, datasource=None): self.__main_window = Tk() self.__main_window.minsize(800, 600) self.__main_window.iconbitmap("resources/quill.ico") self.__main_window.wm_title("Notebook Demo") self.__add_menu() cols = ("Last Name", "First Name", "Phone", "Birthday") tv = Treeview(self.__main_window, columns=cols, show="headings") self.__table = tv for col in cols: tv.heading(col, text=col) tv.grid(row=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W) Tkinter.Grid.columnconfigure(self.__main_window, 0, weight=1) Tkinter.Grid.rowconfigure(self.__main_window, 0, weight=1) Tkinter.Grid.columnconfigure(self.__main_window, 1, minsize=100) self.__add_buttons() # To be able to use this UI from another app and as autonomous app # Also, I just hate an idea of creating storage in UI if datasource is None: self.__datasource = DataStorage() else: self.__datasource = datasource
class App: def __init__(self, window): self.window = window self.mainDaemonAlive = False self.reportServerAlive = False self.reportServerBut = None self.progressbarRunning = False self.modelTree = None self.nsListStr = StringVar(self.window) self.filterStatusStr = StringVar(self.window) self.reportClientStatusStr = StringVar(self.window) self.playModeStr = StringVar(self.window, PLAY_MODES[0]) self.pktCopyMaxSize = StringVar(self.window, "60") self.netInterfaceStr = StringVar(self.window, NET_INTERFACES[0]) self.servicePortsStr = StringVar(self.window, "DNS") self.debugLevelStr = StringVar(self.window, DEBUG_LEVELS[0]) self.filterControlButStr = StringVar(self.window, "START") self.reportClientControlButStr = StringVar(self.window, "START") self.progressFrame = Frame(self.window, width=700, height=20) self.progressFrame.pack(side=TOP) Frame(self.window, width=700, height=10).pack(side=TOP) self.parseNS("/etc/resolv.conf") self.getDaemonStatus() self.home() Frame(self.window, width=700, height=10).pack(side=TOP) self.window.resizable(width=False, height=False) Style().configure("TButton", padding=6, relief="raised", background="#999") def home(self): """ Initialize main window. """ #Configured NS info frame nsFrame = Frame(self.window, relief="groove", borderwidth=1) Label(nsFrame, text="Configured nameservers:", height=2, anchor='w').grid(row=0, sticky="nsew") Label(nsFrame, textvariable=self.nsListStr, relief="sunken").grid(row=1, sticky="nsew") nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) #Runtime params frame nsFrame = Frame(self.window, relief="groove", borderwidth=1) Label(nsFrame, text="Runtime configurations:", height=2, anchor='w').grid(row=0, sticky="nsew") Label(nsFrame, text="Play mode:").grid(row=1, column=0) OptionMenu(nsFrame, self.playModeStr, *PLAY_MODES).grid(row=1, column=1) Separator(nsFrame, orient="vertical").grid(row=1, column=2, sticky="ns", padx=20) Label(nsFrame, text="Interface:").grid(row=1, column=3) OptionMenu(nsFrame, self.netInterfaceStr, *NET_INTERFACES).grid(row=1, column=4) Separator(nsFrame, orient="vertical").grid(row=1, column=5, sticky="ns", padx=20) Label(nsFrame, text="Service:").grid(row=1, column=6) OptionMenu(nsFrame, self.servicePortsStr, *NET_PORTS.keys()).grid(row=1, column=7) Separator(nsFrame, orient="vertical").grid(row=1, column=8, sticky="ns", padx=20) Label(nsFrame, text="Debug level:").grid(row=1, column=9) OptionMenu(nsFrame, self.debugLevelStr, *DEBUG_LEVELS).grid(row=1, column=10) nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(nsFrame, orient="vertical").grid(row=2, column=2, sticky="ns", padx=20) Label(nsFrame, text="Max datagram bytes to copy:").grid(row=2, column=3) Entry(nsFrame, width=5, text=self.pktCopyMaxSize.get(), textvariable=self.pktCopyMaxSize).grid(row=2, column=4) Separator(nsFrame, orient="vertical").grid(row=2, column=5, sticky="ns", padx=20) nsFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) #filter daemon status frame statusFrame = Frame(self.window) Label(statusFrame, text="DNS filter status:", height=2, anchor='w').grid(row=0, column=0) Label(statusFrame, textvariable=self.filterStatusStr).grid(row=0, column=1) Button(statusFrame, textvariable=self.filterControlButStr, command=self.changeFilterStatus).grid(row=1, column=0, sticky=W) statusFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) #model files frame modelFrame = Frame(self.window) Label(modelFrame, text="Model tags: [{}]".format(configs["model_tags"]), height=2, anchor='w').grid(row=0, sticky="nsew") Label(modelFrame, text="Model configuration", height=2).grid(row=1, sticky=W) self.modelConfigFrame(modelFrame).grid(row=2, columnspan=2, sticky=W) modelFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) #web report client frame reportClientFrame = Frame(self.window) Label(reportClientFrame, text="Realtime report client status:", height=2, anchor='w').grid(row=0, column=0) Label(reportClientFrame, textvariable=self.reportClientStatusStr).grid(row=0, column=1) self.reportServerBut = Button( reportClientFrame, textvariable=self.reportClientControlButStr, command=self.changeReportClientStatus, state=self.getButtonStateForBool(self.mainDaemonAlive)) self.reportServerBut.grid(row=1, column=0, sticky=W) reportClientFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) #Refresh status frame reloadFrame = Frame(self.window) Button(reloadFrame, text="Reload", command=self.getDaemonStatus).grid(row=0, column=1, sticky=E) reloadFrame.pack(side=TOP, fill=X, padx=20, pady=10, ipadx=20, ipady=5) Separator(self.window, orient="horizontal").pack(side=TOP, padx=20, fill=X) return def modelConfigFrame(self, parent): """ Create and place next under parent a frame containing the current model configuration. """ #Create container frame = Frame(parent) #Create treeView for model configuration self.modelTree = Treeview(parent, columns=('size', 'modified')) self.populateModelTree() self.modelTree.grid(row=1) #Bind right-click (<Button-3>) on tree items for contextual menus def treeContextualMenu(event): itemId = self.modelTree.identify_row(event.y) if itemId: self.modelTree.selection_set(itemId) item = self.modelTree.selection() ctxMenu = Menu(self.window, tearoff=0) ctxMenu.add_separator() if item[0][:4] == "tag:": tag = item[0][4:] ctxMenu.add_command( label="Add samples (from a csv file)", command=lambda: self.addSampleFileToModelDir(tag)) ctxMenu.add_separator() ctxMenu.add_command( label="Visualize feature map w.r.t loaded model", command=lambda: self.testOnLoadedModel( join(configs["model_data_dir"], tag), True)) elif item[0][:5] == "file:": filename = item[0][5:] ctxMenu.add_command( label="Test on loaded model", command=lambda: self.testOnLoadedModel( join(configs["model_data_dir"], filename), False)) ctxMenu.add_separator() ctxMenu.add_command( label="Delete", command=lambda: self.deleteModelFile(filename)) ctxMenu.add_separator() ctxMenu.tk_popup(event.x_root, event.y_root) self.modelTree.bind("<Button-3>", treeContextualMenu) return frame def testOnLoadedModel(self, sampleFile, isDir): try: modelviz.model_viz(sampleFile, isDir) except Exception as exc: tkMessageBox.showinfo("Sorry!", exc) return def populateModelTree(self): if self.modelTree is None: return #Extract model tags tags = [s.strip() for s in configs["model_tags"].split(",")] self.modelTree.column('size', width=200, anchor='center') self.modelTree.column('modified', width=200, anchor='center') self.modelTree.heading('size', text='Length') self.modelTree.heading('modified', text='Modified') treeHeight = 0 #Populate treeView with current configuration self.modelTree.delete(*self.modelTree.get_children()) for i in range(len(tags)): treeHeight += 1 dirName = join(configs["model_data_dir"], tags[i]) children = self.getDirContentDescr(dirName) rowId = self.modelTree.insert('', i, "tag:{}".format(tags[i]), text=tags[i]) for child in children: treeHeight += 1 self.modelTree.insert( rowId, "end", "file:{}/{}".format(tags[i], child['name']), text=child['name'], values=(child['size'], child['modified'])) self.modelTree['height'] = treeHeight + 1 return def addSampleFileToModelDir(self, tag): modelDir = join(configs["model_data_dir"], tag) file_opts = { 'defaultextension': '.csv', 'filetypes': [('CSV files', '.csv'), ('all files', '.*')], 'initialdir': expanduser("~"), 'title': 'Select data file' } filename = tkFileDialog.askopenfilename(**file_opts) try: modelLoader.add_file_to_model_dir(filename, modelDir) except Exception as exc: tkMessageBox.showerror("Error copying files", exc) return self.populateModelTree() tkMessageBox.showinfo( "Success", "Successfully copied data file {} to {}.".format( filename, modelDir)) return def deleteModelFile(self, filename): if tkMessageBox.askyesno("Confirm deleting {}".format(filename), "Are you sure about deleting this file?"): try: remove(join(configs["model_data_dir"], filename)) self.populateModelTree() except Exception, exc: tkMessageBox.showerror("Error deleting {}".format(filename), exc) return
def show(frame, iterator): """Выводит на экран выборку, заданную в iterator""" scrollbar = Scrollbar(frame) tree = Treeview(frame, selectmode='none', padding=3, style='Custom.Treeview', height=REPORT_HEIGHT, yscrollcommand=scrollbar.set) tree.pack(side=LEFT, fill=BOTH, expand=YES) scrollbar.config(command=tree.yview) scrollbar.pack(side=LEFT, fill=Y) tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT)) tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT), background='#f5f5ff') tree.tag_configure('red1', font=('Verdana', FONT_SIZE_REPORT), foreground='red') tree.tag_configure('red2', font=('Verdana', FONT_SIZE_REPORT), background='#f5f5ff', foreground='red') tree.tag_configure('grey1', font=('Verdana', FONT_SIZE_REPORT), foreground='#dddddd') tree.tag_configure('grey2', font=('Verdana', FONT_SIZE_REPORT), background='#f5f5ff', foreground='#dddddd') Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2) columns = ['#' + str(x + 1) for x in range(4)] tree.configure(columns=columns) for q in range(len(header)): tree.heading('#%d' % (q + 1), text=header[q], anchor='w') tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1], anchor='w') tree.heading('#0', text='', anchor='w') tree.column('#0', width=0, anchor='w', minwidth=0) flag = True for item in iterator: if not item.calculation: col = [] col.append(add_s(item.cathegory.name if item.cathegory else u'-Нет-')) col.append(add_s(item.name)) storage = queries.items_in_storage(item) col.append(add_s(storage)) col.append(add_s(item.measure)) if int(storage) > 0: flag = not flag if flag: tree.insert('', 'end', text='', values=col, tag='2') else: tree.insert('', 'end', text='', values=col, tag='1') elif storage == '0': flag = not flag if flag: tree.insert('', 'end', text='', values=col, tag='grey2') else: tree.insert('', 'end', text='', values=col, tag='grey1') else: flag = not flag if flag: tree.insert('', 'end', text='', values=col, tag='red2') else: tree.insert('', 'end', text='', values=col, tag='red1')
def Continue(self): self.master.withdraw() self.main = Toplevel(self.master) self.main.geometry("%dx%d+%d+%d" % (1038-206, 694, int((500.0/2560.0)*screen_resolution[0]), int((60.0/1440.0)*screen_resolution[1]))) self.main.minsize(376,227) self.interior = PanedWindow(self.main,sashwidth=5) self.interior.pack(fill=BOTH, expand=1) self.elements_frame = Frame(self.interior, height=1038, width=212,relief=RIDGE,borderwidth=0) self.interior.add(self.elements_frame) self.interior.paneconfig(self.elements_frame,minsize=130) self.graph_frame = Frame(self.interior) self.interior.add(self.graph_frame) self.interior.paneconfig(self.graph_frame,minsize=130) self.main.bind("<ButtonRelease-1>",self.pan_update) self.main.bind("<ButtonRelease-3>",self.pan_update) self.main.bind("<Button-3>",self.right_menu) self.edit_frame = Frame(self.graph_frame) self.edit_frame.pack(side=TOP,fill=X,padx=10) self.canvas = FigureCanvasTkAgg(self.Fig, master=self.graph_frame) self.canvas.show() self.canvas.get_tk_widget().pack(fill=BOTH,expand=1) self.nav_frame = Frame(self.edit_frame) self.nav_frame.pack(side=LEFT,anchor=W) self.toolbar = NavigationToolbar(self.canvas, self.nav_frame) self.main.protocol('WM_DELETE_WINDOW',self.master.destroy) self.elements = Treeview(self.elements_frame,columns=("values","xlocations","ylocations"),selectmode=BROWSE) self.elements.heading("#0",text="Components") self.elements.heading("values",text="Str") self.elements.heading("xlocations",text="X") self.elements.heading("ylocations",text="Y") self.elements.column("#0",width=90,anchor=CENTER) self.elements.column("values",width=45,anchor=CENTER) self.elements.column("xlocations",width=26,anchor=CENTER) self.elements.column("ylocations",width=26,anchor=CENTER) self.elements.pack(fill=BOTH,expand=1) self.as_button_frame = Frame(self.elements_frame) self.add_button = Button(self.as_button_frame,text = '+',width=2,command=self.add) self.sub_button = Button(self.as_button_frame,text = '-',width=2,command=self.subtract) self.options_button = Button(self.as_button_frame,text='Options',command=self.options) self.as_button_frame.pack(side=BOTTOM,anchor=W) self.options_button.pack(side=RIGHT) self.sub_button.pack(side=RIGHT,anchor=W) self.add_button.pack(side=LEFT,anchor=W) self.addsub_menu = Menu(self.as_button_frame,tearoff=0) self.addsub_menu.add_command(command=self.add_source,label='Source') self.addsub_menu.add_command(command=self.add_vortex,label='Vortex') self.addsub_menu.add_command(command=self.add_uniform,label='Uniform') self.addsub_menu.add_command(command=self.add_doublet,label='Doublet') self.addsub_menu.add_command(command=self.add_corner,label='Corner') #if self.listbox.get(self.listbox.curselection()) == 'Default': if self.radio_var.get() == 'Default': self.active_components = [] self.active_calls = {} pass #elif self.listbox.get(self.listbox.curselection()) == 'Maelstrom': elif self.radio_var.get() == 'Maelstrom': self.elements.insert("",0,"M",text="Maelstrom",open=TRUE) self.active_components = ['M'] self.elements.insert("M",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%1,0,0)) self.elements.insert("M",0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%1,0,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))} self.active_numbers['s'] += 1 self.active_numbers['v'] += 1 elif self.radio_var.get() == 'Rankine Half-Body': self.elements.insert("",0,"RHF",text="Rankine Half-Body",open=TRUE) self.active_components = ['RHF'] self.elements.insert("RHF",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,0,0)) self.elements.insert("RHF",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['s'] += 1 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Rankine Oval': self.elements.insert("",0,"RO",text="Rankine Oval",open=TRUE) self.active_components = ['RO'] self.elements.insert("RO",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,-2,0)) self.elements.insert("RO",0,iid='s%s'%(self.active_numbers['s']+1),text="Source",values=("%s"%-10,2,0)) self.elements.insert("RO",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 's%s'%(self.active_numbers['s']+1):("s",self.elements.item('s%s'%(self.active_numbers['s']+1),"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['s'] += 2 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Cylinder': self.elements.insert("",0,'D+U',text="Cylinder",open=TRUE) self.active_components = ['D+U'] self.elements.insert('D+U',0,iid='d%s'%self.active_numbers['d'],text="Doublet",values=("%s"%25,0,0)) self.elements.insert('D+U',0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'d%s'%self.active_numbers['d']:("d",self.elements.item('d%s'%self.active_numbers['d'],"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['d'] += 1 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Stagnation & Vortex': self.elements.insert("",0,'S+V',text="Stag+Vort",open=TRUE) self.active_components = ['S+V'] self.elements.insert('S+V',0,iid='n%s'%self.active_numbers['n'],text="C (n,A)",values=("%s,%s"%(2,1),0,0)) self.elements.insert('S+V',0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%25,0,0)) self.active_calls = {'n%s'%self.active_numbers['n']:("n",self.elements.item('n%s'%self.active_numbers['n'],"values")), 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))} self.active_numbers['n'] += 1 self.active_numbers['v'] += 1 self.elements.bind("<Double-Button-1>",self.edit) self.elements.bind('<<TreeviewSelect>>',self.treeview_select) self.main.bind("<Return>",self.edit_return) self.main.bind("<Escape>",self.edit_return) self.rightc_menu = Menu(self.graph_frame,tearoff=0) self.add_menu = Menu(self.rightc_menu,tearoff=0) self.rightc_menu.add_cascade(label="Add",menu=self.add_menu) self.add_menu.add_command(command=self.addm_source,label='Source') self.add_menu.add_command(command=self.addm_vortex,label='Vortex') self.add_menu.add_command(command=self.addm_uniform,label='Uniform') self.add_menu.add_command(command=self.addm_doublet,label='Doublet') self.add_menu.add_command(command=self.addm_corner,label='Corner')
class App: def __init__(self,master): self.master = master self.master.resizable(0,0) self.master.update_idletasks() self.master.overrideredirect(1) self.master.attributes("-topmost",True) self.master.title("New Graph") self.master.lift() self.menubar = Menu(self.master) self.master.config(menu=self.menubar) self.default_color = self.master.cget("bg") self.active_edit_flag = 0 self.modify_flag = 0 self.graph_types = ['Default','Maelstrom','Rankine Half-Body','Rankine Oval', 'Cylinder','Stagnation & Vortex'] #----------------------------------------------------------------------- self.file_menu = Menu(self.menubar) self.Fig = matplotlib.figure.Figure(figsize=(2.148,1.777),dpi=100,tight_layout=True) self.FigSubPlot = self.Fig.add_subplot(111) frame = Frame(master,bg='#%02x%02x%02x' % (231, 231, 231)) frame.pack(fill=BOTH, expand=1) frame2 = Frame(frame,bg='#%02x%02x%02x' % (221, 221, 221)) frame2.pack(fill=BOTH, expand=1,padx=20,pady=23) self.frame3 = Frame(frame2, bg='#%02x%02x%02x' % (221, 221, 221)) self.frame3.pack(fill=BOTH, padx=17,pady=17,expand=1) self.radio_frame = Frame(self.frame3,bg='#%02x%02x%02x' % (221, 221, 221)) #self.listbox = Listbox(self.frame3) self.radio_var = StringVar() self.radio_var.set('Default') for key in self.graph_types: b = Radiobutton(self.radio_frame,text=key,variable=self.radio_var,value = key,bg='#%02x%02x%02x' % (221, 221, 221),indicatoron=1) b.pack(anchor=W) # for key_num in range(0,len(self.graph_types)): # self.listbox.insert(END,self.graph_types[key_num]) # self.listbox.select_set(0) # self.listbox.bind('<<ListboxSelect>>',self.changegraph) self.radio_var.trace('w',self.changegraph) # self.old = self.listbox.get(self.listbox.curselection()) self.blankc = Canvas(self.frame3,width=225,height=188) self.canvas = FigureCanvasTkAgg(self.Fig, master=self.frame3) self.canvas.show() self.canvas.get_tk_widget().pack(side=RIGHT,padx=0,pady=5) self.radio_frame.pack(side=LEFT,anchor=W,padx=8,pady=5,fill=BOTH,expand=1) #self.listbox.pack(side=LEFT,anchor=W,padx=8,pady=5,fill=BOTH,expand=1) self.button_frame = Frame(frame,bg='#%02x%02x%02x' % (231, 231, 231)) self.button_frame.pack(side=RIGHT) self.buffer_frame = Frame(self.button_frame,bg='#%02x%02x%02x' % (231, 231, 231)) self.buffer_frame.pack(side=BOTTOM,pady=8) self.buffer_frame2 = Frame(self.button_frame,bg='#%02x%02x%02x' % (231, 231, 231)) self.buffer_frame2.pack(side=RIGHT,padx=11) self.button_c = Button(self.button_frame,width=9, text='Choose',bg='#%02x%02x%02x' % (231, 231, 231),command=self.Continue) self.button_x = Button(self.button_frame,text='Cancel',bg='#%02x%02x%02x' % (231, 231, 231),width=9,command=self.quit) self.button_c.focus() self.button_c.pack(side=RIGHT) self.button_x.pack(side=RIGHT,padx=14) self.line_color = StringVar() self.line_color.set('#000000') self.wt_var = StringVar() self.wt_var.set('- WT:') self.wt_var.trace('w',self.wt_update) self.linet_var = StringVar() self.linet_var.set('-') self.linet_var.trace('w',self.line_style_update) self.line_var = IntVar() self.line_var.set(25) self.line_val = 25 self.div_check_var = IntVar() self.div_check_var.set(50) self.div_val = 50 self.density_var = IntVar() self.density_var.set(35) self.density_val = 35 self.arrow_var = IntVar() self.arrow_var.set(25) self.arrow_val = 25 self.div_var = IntVar() self.div_var.set(0) self.mark_var = IntVar() self.mark_var.set(0) self.lock_var = IntVar() self.lock_var.set(1) self.active_numbers = {'s':0,'v':0,'u':0,'d':0,'n':0} self.sel_point = None self.selected = None def changegraph(self,*args): self.xlim = [-5.0,5.0] self.ylim = [-5.0,5.0] Y, X = mgrid[-5:5:100j, -5:5:100j] self.X,self.Y = X,Y self.FigSubPlot.clear() #if self.listbox.get(self.listbox.curselection()) == 'Default': if self.radio_var.get() == 'Default': self.U = 0*X self.V = 0*X self.FigSubPlot.streamplot(X,Y,self.U,self.V) #elif self.listbox.get(self.listbox.curselection()) == 'Maelstrom': elif self.radio_var.get() == 'Maelstrom': self.U = self.source(X,Y,1)[0]+self.vortex(X,Y,1)[0] self.V = self.source(X,Y,1)[1]+self.vortex(X,Y,1)[1] self.FigSubPlot.streamplot(X,Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-') #elif self.listbox.get(self.listbox.curselection()) == 'Rankine Half-Body': elif self.radio_var.get() == 'Rankine Half-Body': self.U = self.source(X,Y,10)[0]+self.uniform(X,Y,1,1,0)[0] self.V = self.source(X,Y,10)[1]+self.uniform(X,Y,1,1,0)[1] self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-') #elif self.listbox.get(self.listbox.curselection()) == 'Rankine Oval': elif self.radio_var.get() == 'Rankine Oval': self.U = self.source(X+2,Y,10)[0]+self.source(X-2,Y,-10)[0]+self.uniform(X,Y,1,1,0)[0] self.V = self.source(X+2,Y,10)[1]+self.source(X-2,Y,-10)[1]+self.uniform(X,Y,1,1,0)[1] self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-') #elif self.listbox.get(self.listbox.curselection()) == 'Cylinder': elif self.radio_var.get() == 'Cylinder': self.U = self.doublet(X,Y,25)[0]+self.uniform(X,Y,1,1,0)[0] self.V = self.doublet(X,Y,25)[1]+self.uniform(X,Y,1,1,0)[1] self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-') #elif self.listbox.get(self.listbox.curselection()) == 'Stagnation & Vortex': elif self.radio_var.get() == 'Stagnation & Vortex': self.U = self.vortex(X,Y,25)[0]+self.corner(X,Y,'2,1')[0] self.V = self.vortex(X,Y,25)[1]+self.corner(X,Y,'2,1')[1] self.FigSubPlot.streamplot(X, Y,self.U,self.V, color='k', linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle='-') self.FigSubPlot.set_xlim(self.xlim) self.FigSubPlot.set_ylim(self.ylim) self.canvas.draw() # self.old = self.listbox.get(self.listbox.curselection()) def source(self,X,Y,l): l = float(l) U = (l/(2*pi))*X/(X*X + Y*Y) V = (l/(2*pi))*Y/(X*X + Y*Y) return (U,V) def vortex(self,X,Y,g): g = float(g) U = (g/(2*pi))*Y/(X*X + Y*Y) V = (g/(2*pi))*-X/(X*X + Y*Y) return (U,V) def uniform(self,X,Y,v_0,x_0,y_0): v_0 = float(v_0) x_0 = float(x_0) y_0 = float(y_0) U = v_0*x_0/(x_0*x_0+y_0*y_0)**0.5 V = v_0*y_0/(x_0*x_0+y_0*y_0)**0.5 return (U,V) def doublet(self,X,Y,k): k = float(k) U = (k/(2*pi))*((2*Y*Y/((X*X+Y*Y)*(X*X+Y*Y)))-(1/(X*X+Y*Y))) V = -(k/(2*pi))*(2*X*Y/((X*X+Y*Y)*(X*X+Y*Y))) return (U,V) def corner(self,X,Y,tup): comma_flag = 0 A = '' n = '' for char in tup: if char == ',': comma_flag = 1 elif comma_flag == 0: n += char elif comma_flag == 1: A += char A = float(A) n = float(n) R = (X*X+Y*Y)**0.5 t = arctan2(-Y,-X) U = -A*n*R**(n-1)*(cos(n*t)*cos(t)+sin(n*t)*sin(t)) V = -A*n*R**(n-1)*(cos(n*t)*sin(t)-sin(n*t)*cos(t)) return (U,V) def stream_source(self,X,Y,l): l = float(l) stream = (l/(2*pi))*arctan2(-Y,-X) return stream def stream_vortex(self,X,Y,g): g = float(g) stream = (g/(2*pi))*log((X*X + Y*Y)**0.5) return stream def stream_uniform(self,X,Y,v_0,x_0,y_0): v_0 = float(v_0) x_0 = float(x_0) y_0 = float(y_0) stream = (v_0*Y*x_0/(x_0*x_0+y_0*y_0)**0.5)-(v_0*X*y_0/(x_0*x_0+y_0*y_0)**0.5) return stream def stream_doublet(self,X,Y,k): k = float(k) stream = -(k/(2*pi))*Y/(X*X+Y*Y) return stream def stream_corner(self,X,Y,tup): comma_flag = 0 A = '' n = '' for char in tup: if char == ',': comma_flag = 1 elif comma_flag == 0: n += char elif comma_flag == 1: A += char A = float(A) n = float(n) stream = A*(X*X+Y*Y)**(n*0.5)*sin(n*arctan2(-Y,-X)) return stream def quit(self): self.master.destroy() def Continue(self): self.master.withdraw() self.main = Toplevel(self.master) self.main.geometry("%dx%d+%d+%d" % (1038-206, 694, int((500.0/2560.0)*screen_resolution[0]), int((60.0/1440.0)*screen_resolution[1]))) self.main.minsize(376,227) self.interior = PanedWindow(self.main,sashwidth=5) self.interior.pack(fill=BOTH, expand=1) self.elements_frame = Frame(self.interior, height=1038, width=212,relief=RIDGE,borderwidth=0) self.interior.add(self.elements_frame) self.interior.paneconfig(self.elements_frame,minsize=130) self.graph_frame = Frame(self.interior) self.interior.add(self.graph_frame) self.interior.paneconfig(self.graph_frame,minsize=130) self.main.bind("<ButtonRelease-1>",self.pan_update) self.main.bind("<ButtonRelease-3>",self.pan_update) self.main.bind("<Button-3>",self.right_menu) self.edit_frame = Frame(self.graph_frame) self.edit_frame.pack(side=TOP,fill=X,padx=10) self.canvas = FigureCanvasTkAgg(self.Fig, master=self.graph_frame) self.canvas.show() self.canvas.get_tk_widget().pack(fill=BOTH,expand=1) self.nav_frame = Frame(self.edit_frame) self.nav_frame.pack(side=LEFT,anchor=W) self.toolbar = NavigationToolbar(self.canvas, self.nav_frame) self.main.protocol('WM_DELETE_WINDOW',self.master.destroy) self.elements = Treeview(self.elements_frame,columns=("values","xlocations","ylocations"),selectmode=BROWSE) self.elements.heading("#0",text="Components") self.elements.heading("values",text="Str") self.elements.heading("xlocations",text="X") self.elements.heading("ylocations",text="Y") self.elements.column("#0",width=90,anchor=CENTER) self.elements.column("values",width=45,anchor=CENTER) self.elements.column("xlocations",width=26,anchor=CENTER) self.elements.column("ylocations",width=26,anchor=CENTER) self.elements.pack(fill=BOTH,expand=1) self.as_button_frame = Frame(self.elements_frame) self.add_button = Button(self.as_button_frame,text = '+',width=2,command=self.add) self.sub_button = Button(self.as_button_frame,text = '-',width=2,command=self.subtract) self.options_button = Button(self.as_button_frame,text='Options',command=self.options) self.as_button_frame.pack(side=BOTTOM,anchor=W) self.options_button.pack(side=RIGHT) self.sub_button.pack(side=RIGHT,anchor=W) self.add_button.pack(side=LEFT,anchor=W) self.addsub_menu = Menu(self.as_button_frame,tearoff=0) self.addsub_menu.add_command(command=self.add_source,label='Source') self.addsub_menu.add_command(command=self.add_vortex,label='Vortex') self.addsub_menu.add_command(command=self.add_uniform,label='Uniform') self.addsub_menu.add_command(command=self.add_doublet,label='Doublet') self.addsub_menu.add_command(command=self.add_corner,label='Corner') #if self.listbox.get(self.listbox.curselection()) == 'Default': if self.radio_var.get() == 'Default': self.active_components = [] self.active_calls = {} pass #elif self.listbox.get(self.listbox.curselection()) == 'Maelstrom': elif self.radio_var.get() == 'Maelstrom': self.elements.insert("",0,"M",text="Maelstrom",open=TRUE) self.active_components = ['M'] self.elements.insert("M",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%1,0,0)) self.elements.insert("M",0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%1,0,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))} self.active_numbers['s'] += 1 self.active_numbers['v'] += 1 elif self.radio_var.get() == 'Rankine Half-Body': self.elements.insert("",0,"RHF",text="Rankine Half-Body",open=TRUE) self.active_components = ['RHF'] self.elements.insert("RHF",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,0,0)) self.elements.insert("RHF",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['s'] += 1 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Rankine Oval': self.elements.insert("",0,"RO",text="Rankine Oval",open=TRUE) self.active_components = ['RO'] self.elements.insert("RO",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%10,-2,0)) self.elements.insert("RO",0,iid='s%s'%(self.active_numbers['s']+1),text="Source",values=("%s"%-10,2,0)) self.elements.insert("RO",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'s%s'%self.active_numbers['s']:("s",self.elements.item('s%s'%self.active_numbers['s'],"values")), 's%s'%(self.active_numbers['s']+1):("s",self.elements.item('s%s'%(self.active_numbers['s']+1),"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['s'] += 2 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Cylinder': self.elements.insert("",0,'D+U',text="Cylinder",open=TRUE) self.active_components = ['D+U'] self.elements.insert('D+U',0,iid='d%s'%self.active_numbers['d'],text="Doublet",values=("%s"%25,0,0)) self.elements.insert('D+U',0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,1,0)) self.active_calls = {'d%s'%self.active_numbers['d']:("d",self.elements.item('d%s'%self.active_numbers['d'],"values")), 'u%s'%self.active_numbers['u']:("u",self.elements.item('u%s'%self.active_numbers['u'],"values"))} self.active_numbers['d'] += 1 self.active_numbers['u'] += 1 elif self.radio_var.get() == 'Stagnation & Vortex': self.elements.insert("",0,'S+V',text="Stag+Vort",open=TRUE) self.active_components = ['S+V'] self.elements.insert('S+V',0,iid='n%s'%self.active_numbers['n'],text="C (n,A)",values=("%s,%s"%(2,1),0,0)) self.elements.insert('S+V',0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%25,0,0)) self.active_calls = {'n%s'%self.active_numbers['n']:("n",self.elements.item('n%s'%self.active_numbers['n'],"values")), 'v%s'%self.active_numbers['v']:("v",self.elements.item('v%s'%self.active_numbers['v'],"values"))} self.active_numbers['n'] += 1 self.active_numbers['v'] += 1 self.elements.bind("<Double-Button-1>",self.edit) self.elements.bind('<<TreeviewSelect>>',self.treeview_select) self.main.bind("<Return>",self.edit_return) self.main.bind("<Escape>",self.edit_return) self.rightc_menu = Menu(self.graph_frame,tearoff=0) self.add_menu = Menu(self.rightc_menu,tearoff=0) self.rightc_menu.add_cascade(label="Add",menu=self.add_menu) self.add_menu.add_command(command=self.addm_source,label='Source') self.add_menu.add_command(command=self.addm_vortex,label='Vortex') self.add_menu.add_command(command=self.addm_uniform,label='Uniform') self.add_menu.add_command(command=self.addm_doublet,label='Doublet') self.add_menu.add_command(command=self.addm_corner,label='Corner') def right_menu(self,event): print "event", event.x,event.y #print "graph", self.main.winfo_x()+self.interior.winfo_x()+self.graph_frame.winfo_x(), self.main.winfo_y()+self.interior.winfo_y()+self.graph_frame.winfo_y() self.plot_x,self.plot_y = self.FigSubPlot.transData.inverted().transform((event.x,event.y+20)) self.plot_y = -self.plot_y self.rightc_menu.post(self.main.winfo_x()+self.interior.winfo_x()+self.graph_frame.winfo_x()+event.x+9,self.main.winfo_y()+self.graph_frame.winfo_y()+event.y+66) def treeview_select(self,event): if self.elements.get_children(self.elements.selection()[0]) == (): if self.mark_var.get() == 0 or self.selected == self.elements.selection(): pass elif self.mark_var.get() == 1: #add red markers here if self.elements.selection() != '': child = self.elements.selection()[0] if child != '': self.sel_point = (self.elements.item(child,"values")[1],self.elements.item(child,"values")[2]) self.graph_update() self.selected = self.elements.selection() else: pass else: if self.mark_var.get() == 0 or self.selected == self.elements.selection(): pass elif self.mark_var.get() == 1: if self.elements.selection() != '': child = self.elements.selection()[0] if child != '': self.sel_point = None self.graph_update() self.selected = self.elements.selection() def mark_check_fun(self): if self.mark_var.get() == 0: self.sel_point = None self.graph_update() elif self.elements.selection() != '': child = self.elements.selection()[0] self.sel_point = [self.elements.item(child,"values")[1],self.elements.item(child,"values")[2]] self.graph_update() def add(self): self.addsub_menu.post(self.main.winfo_x()+self.as_button_frame.winfo_x()+self.add_button.winfo_x(),self.main.winfo_y()+self.as_button_frame.winfo_y()+self.add_button.winfo_y()-len(self.active_numbers.keys())*14) def subtract(self): if self.active_edit_flag == 1: self.del_edit(self) child = self.elements.selection()[0] if child == '': return if self.elements.parent(child) == '': ID = child self.active_components.remove(child) self.elements.delete(child) else: ID = self.elements.parent(child) self.active_components.remove(ID) for comp in self.elements.get_children(ID): if comp != child: self.active_components.append(comp) self.elements.move(comp,"",0) self.elements.delete(ID) self.sel_point = None self.graph_update() def options(self): self.options_window = Toplevel(self.main) self.options_window.geometry("%dx%d+%d+%d" % (280, 200+20, self.main.winfo_x()+self.as_button_frame.winfo_x()+self.options_button.winfo_x()-272+26+72+86, self.main.winfo_y()+self.as_button_frame.winfo_y()+self.options_button.winfo_y()-196-20)) self.main.bind('<FocusIn>',self.close_options) self.options_window.title("Options") self.options_window.update_idletasks() self.options_window.bind("<ButtonRelease-1>",self.pan_update) self.options_frame = Frame(self.options_window) self.options_frame.pack(fill=BOTH,expand=1) self.options_window.attributes("-topmost",True) self.line_frame = Frame(self.options_frame,bd=2,relief=RIDGE) self.line_frame.grid(row=0,column=1,sticky=N+S+E+W,ipady=7) self.color_frame = Frame(self.options_frame,bd=2,relief=RIDGE,padx=2) self.color_frame.grid(row=0,column=0,sticky=N+S+E+W) self.color_button = Label(self.color_frame,bg=self.line_color.get(),text = ' ') self.color_button.pack(side=RIGHT) Label(self.color_frame,text='C:').pack(side=RIGHT) self.color_button.bind('<Button-1>',self.getColor) self.wt_slider = Scale(self.line_frame,from_=1,to=100,orient=HORIZONTAL,variable=self.line_var) if self.wt_var.get() == '-> WT:': self.wt_slider.config(variable=self.arrow_var) elif self.wt_var.get() == '- WT:': self.wt_slider.config(variable=self.line_var) elif self.wt_var.get() == 'div WT:': self.wt_slider.config(variable=self.div_check_var) self.wt_slider.pack(side=RIGHT) self.wt_menu = OptionMenu(self.line_frame,self.wt_var,'- WT:','-> WT:','div WT:') self.wt_menu.pack(side=RIGHT,anchor='center',fill=X,expand=1) self.wt_menu.config(width=8) self.density_frame = Frame(self.options_frame,bd=2,relief=RIDGE) self.density_frame.grid(row=1,column=1,sticky=N+S+E+W) self.density_slider = Scale(self.density_frame,from_=1,to=100,orient=HORIZONTAL,variable=self.density_var) self.density_slider.pack(side=RIGHT) Label(self.density_frame,text='Density').pack(side=LEFT,anchor=CENTER,fill=X,expand=1) self.linet_frame = Frame(self.options_frame,bd=2,relief=RIDGE) self.linet_frame.grid(row=1,column=0,sticky=N+S+E+W) Label(self.linet_frame,text='Style').pack(anchor='n') self.linet_menu = OptionMenu(self.linet_frame,self.linet_var,'-','->','-|>') self.linet_menu.pack(anchor='s',side=BOTTOM) self.linet_menu.config(width=5) self.div_check = Checkbutton(self.options_frame,text = 'Dividing Streamline',variable=self.div_var,onvalue=1,offvalue=0,command = self.graph_update) self.div_check.grid(row=2,column=1,sticky=W) self.mark_check = Checkbutton(self.options_frame,text = 'Selection Marker',variable=self.mark_var,onvalue=1,offvalue=0,command = self.mark_check_fun) self.mark_check.grid(row=3,column=1,sticky=W) self.limit_frame = Frame(self.options_frame) self.limit_frame.grid(row=4,column=1,sticky=W) #self.aspect_lock = Checkbutton(self.limit_frame,text='LK',variable = self.lock_var) #self.aspect_lock.grid(row=0,column=4,rowspan=2,sticky=E) Label(self.limit_frame,text='x').grid(row=0,column=0) self.xlimlow_var = DoubleVar() self.xlimlow_var.set(self.FigSubPlot.get_xlim()[0]) self.xlimlow_entry = Entry(self.limit_frame,textvariable=self.xlimlow_var,width=5) self.xlimlow_entry.grid(row=0,column=1) Label(self.limit_frame,text='...').grid(row=0,column=2) self.xlimhigh_var = DoubleVar() self.xlimhigh_var.set(self.FigSubPlot.get_xlim()[1]) self.xlimhigh_entry = Entry(self.limit_frame,textvariable=self.xlimhigh_var,width=5) self.xlimhigh_entry.grid(row=0,column=3) Label(self.limit_frame,text='y').grid(row=1,column=0) self.ylimlow_var = DoubleVar() self.ylimlow_var.set(self.FigSubPlot.get_ylim()[0]) self.ylimlow_entry = Entry(self.limit_frame,textvariable=self.ylimlow_var,width=5) self.ylimlow_entry.grid(row=1,column=1) Label(self.limit_frame,text='...').grid(row=1,column=2) self.ylimhigh_var = DoubleVar() self.ylimhigh_var.set(self.FigSubPlot.get_ylim()[1]) self.ylimhigh_entry = Entry(self.limit_frame,textvariable=self.ylimhigh_var,width=5) self.ylimhigh_entry.grid(row=1,column=3) #self.limit_frame.bind('<FocusOut>',self.limits_update) self.xlimhigh_var.trace('w',self.limits_update) self.ylimhigh_var.trace('w',self.limits_update) self.xlimlow_var.trace('w',self.limits_update) self.ylimlow_var.trace('w',self.limits_update) def limits_update(self,*args): if self.xlimlow_entry.get() == '' or self.ylimlow_entry.get() == '' or self.xlimhigh_entry.get() == '' or self.ylimhigh_entry.get() == '': pass elif self.xlimlow_entry.get() == '-' or self.ylimlow_entry.get() == '-' or self.xlimhigh_entry.get() == '-' or self.ylimhigh_entry.get() == '-': pass elif self.xlimlow_entry.get() == '.' or self.ylimlow_entry.get() == '.' or self.xlimhigh_entry.get() == '.' or self.ylimhigh_entry.get() == '.': pass else: self.xlim = [float(self.xlimlow_var.get()),float(self.xlimhigh_var.get())] self.ylim = [float(self.ylimlow_var.get()),float(self.ylimhigh_var.get())] self.FigSubPlot.set_xlim(self.xlim) self.FigSubPlot.set_ylim(self.ylim) self.graph_update() def getColor(self,event): color=askcolor(self.line_color.get()) if color != "None": self.line_color.set(color[1]) self.graph_update() def wt_update(self,*args): if self.wt_var.get() == '-> WT:': self.wt_slider.config(variable=self.arrow_var) elif self.wt_var.get() == '- WT:': self.wt_slider.config(variable=self.line_var) elif self.wt_var.get() == 'div WT:': self.wt_slider.config(variable=self.div_check_var) def line_style_update(self,*args): self.graph_update() def close_options(self,event): self.options_window.destroy() def add_source(self): if self.modify_flag == 0: self.plot_x,self.plot_y = 0,0 self.elements.insert("",0,iid='s%s'%self.active_numbers['s'],text="Source",values=("%s"%1,self.plot_x,self.plot_y)) self.active_calls['s%s'%self.active_numbers['s']] = ("s",self.elements.item('s%s'%self.active_numbers['s'],"values")) self.active_components.append('s%s'%self.active_numbers['s']) if self.modify_flag == 1: self.elements.selection_set('s%s'%self.active_numbers['s']) self.modify_flag = 0 self.graph_update() self.active_numbers['s'] += 1 def add_vortex(self): if self.modify_flag == 0: self.plot_x,self.plot_y = 0,0 self.elements.insert("",0,iid='v%s'%self.active_numbers['v'],text="Vortex",values=("%s"%1,self.plot_x,self.plot_y)) self.active_calls['v%s'%self.active_numbers['v']] = ("v",self.elements.item('v%s'%self.active_numbers['v'],"values")) self.active_components.append('v%s'%self.active_numbers['v']) if self.modify_flag == 1: self.elements.selection_set('v%s'%self.active_numbers['v']) self.modify_flag = 0 self.graph_update() self.active_numbers['v'] += 1 def add_uniform(self): if self.modify_flag == 0: self.plot_x,self.plot_y = 1,0 self.elements.insert("",0,iid='u%s'%self.active_numbers['u'],text="Uniform",values=("%s"%1,self.plot_x,self.plot_y)) self.active_calls['u%s'%self.active_numbers['u']] = ("u",self.elements.item('u%s'%self.active_numbers['u'],"values")) self.active_components.append('u%s'%self.active_numbers['u']) if self.modify_flag == 1: self.elements.selection_set('u%s'%self.active_numbers['u']) self.modify_flag = 0 self.graph_update() self.active_numbers['u'] += 1 def add_doublet(self): if self.modify_flag == 0: self.plot_x,self.plot_y = 0,0 self.elements.insert("",0,iid='d%s'%self.active_numbers['d'],text="Doublet",values=("%s"%1,self.plot_x,self.plot_y)) self.active_calls['d%s'%self.active_numbers['d']] = ("d",self.elements.item('d%s'%self.active_numbers['d'],"values")) self.active_components.append('d%s'%self.active_numbers['d']) if self.modify_flag == 1: self.elements.selection_set('d%s'%self.active_numbers['d']) self.modify_flag = 0 self.graph_update() self.active_numbers['d'] += 1 def add_corner(self): if self.modify_flag == 0: self.plot_x,self.plot_y = 0,0 self.elements.insert("",0,iid='n%s'%self.active_numbers['n'],text="Corner (n,A)",values=("%s,%s"%(2,1),self.plot_x,self.plot_y)) self.active_calls['n%s'%self.active_numbers['n']] = ("n",self.elements.item('n%s'%self.active_numbers['n'],"values")) self.active_components.append('n%s'%self.active_numbers['n']) if self.modify_flag == 1: self.elements.selection_set('n%s'%self.active_numbers['n']) self.modify_flag = 0 self.graph_update() self.active_numbers['n'] += 1 def addm_source(self): self.modify_flag = 1 self.add_source() def addm_vortex(self): self.modify_flag = 1 self.add_vortex() def addm_uniform(self): self.modify_flag = 1 self.add_uniform() def addm_doublet(self): self.modify_flag = 1 self.add_doublet() def addm_corner(self): self.modify_flag = 1 self.add_corner() def pan_update(self,event): if [self.FigSubPlot.get_xlim()[0],self.FigSubPlot.get_xlim()[1]] != self.xlim or [self.FigSubPlot.get_ylim()[0],self.FigSubPlot.get_ylim()[1]] != self.ylim or self.density_var.get() != self.density_val or self.line_var.get() != self.line_val or self.arrow_var.get() != self.arrow_val or self.arrow_var.get() != self.arrow_val or self.div_check_var.get() != self.div_val: self.graph_update() self.density_val = self.density_var.get() self.line_val = self.line_var.get() self.arrow_val = self.arrow_var.get() self.div_val = self.div_check_var.get() else: return def graph_update(self): self.FigSubPlot.clear() Y, X = mgrid[self.FigSubPlot.get_ylim()[0]:self.FigSubPlot.get_ylim()[1]:100j, self.FigSubPlot.get_xlim()[0]:self.FigSubPlot.get_xlim()[1]:100j] self.xlim = [self.FigSubPlot.get_xlim()[0],self.FigSubPlot.get_xlim()[1]] self.ylim = [self.FigSubPlot.get_ylim()[0],self.FigSubPlot.get_ylim()[1]] self.U = 0*X self.V = 0*X self.stream = 0*X for ID in self.active_components: if self.elements.get_children(ID) == (): child = ID self.active_calls[child] = (child[0],self.elements.item(child,"values")) if self.active_calls[child][0] == "s": self.U += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'v': self.U += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'u': if self.active_calls[child][1][1] == '0' and self.active_calls[child][1][2] == '0': pass else: self.U += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[0] self.V += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[1] self.stream += self.stream_uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2]) elif self.active_calls[child][0] == 'd': self.U += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'n': self.U += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) else: for child in self.elements.get_children(ID): self.active_calls[child] = (child[0],self.elements.item(child,"values")) if self.active_calls[child][0] == "s": self.U += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_source(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'v': self.U += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_vortex(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'u': if self.active_calls[child][1][1] == '0' and self.active_calls[child][1][2] == '0': pass else: self.U += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[0] self.V += self.uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2])[1] self.stream += self.stream_uniform(X,Y,self.active_calls[child][1][0],self.active_calls[child][1][1],self.active_calls[child][1][2]) elif self.active_calls[child][0] == 'd': self.U += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_doublet(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) elif self.active_calls[child][0] == 'n': self.U += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[0] self.V += self.corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0])[1] self.stream += self.stream_corner(X-float(self.active_calls[child][1][1]),Y-float(self.active_calls[child][1][2]),self.active_calls[child][1][0]) self.FigSubPlot.streamplot(X,Y,self.U,self.V,color=self.line_color.get(), linewidth=(2.0/71.0)*self.line_var.get()+(13.0/71.0),density=(2.0/71.0)*self.density_var.get()+(13.0/71.0),arrowstyle=self.linet_var.get(),arrowsize=(4.0/71.0)*self.arrow_var.get()+(13.0/71.0)) if self.div_var.get() == 1: #self.FigSubPlot.contour(X,Y,self.stream,[-0.01,0.01],linewidths=[(4.0/71.0)*self.div_check_var.get()+(13.0/71.0),(4.0/71.0)*self.div_check_var.get()+(13.0/71.0)]) self.FigSubPlot.contour(X,Y,self.stream,[0],linewidths=[(4.0/71.0)*self.div_check_var.get()+(13.0/71.0)]) if self.mark_var.get() == 1: if self.sel_point != None: self.plot_point() self.FigSubPlot.set_xlim(self.xlim) self.FigSubPlot.set_ylim(self.ylim) self.canvas.draw() def plot_point(self): if self.elements.selection()[0][0] == 'u': norm = float(float(self.sel_point[0])*float(self.sel_point[0])+float(self.sel_point[1])*float(self.sel_point[1]))**0.5 if norm == 0: norm = 1 X,Y,U,V = 0,0, float(self.sel_point[0])/norm,float(self.sel_point[1])/norm self.FigSubPlot.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1,color='g') else: self.FigSubPlot.plot([self.sel_point[0]],[self.sel_point[1]],'r^',ms=10) def edit(self,event): if self.active_edit_flag == 1 or self.elements.identify_row(event.y) == '': pass else: self.rowid = self.elements.identify_row(event.y) self.column = self.elements.identify_column(event.x) self.edit_var = StringVar() if int(self.column[-1]) == 0: self.edit_var.set('%s'%self.elements.item("%s"%self.elements.identify("item",event.x, event.y))['text']) else: self.edit_var.set('%s'%self.elements.item("%s"%self.elements.identify("item",event.x, event.y))['values'][int(self.column[-1])-1]) x,y,width,height = self.elements.bbox(self.rowid, self.column) self.edit_entry = Entry(self.elements_frame,textvariable=self.edit_var) self.edit_entry.place(x=x,y=y,width=width) self.edit_entry.focus_force() self.edit_entry.bind("<FocusOut>", self.del_edit) self.active_edit_flag = 1 def edit_return(self,event): self.main.focus() def del_edit(self,event): if self.column[-1] == '0': self.elements.item(self.rowid,text='%s'%self.edit_var.get()) elif self.rowid[0] == 'n' and self.column[-1] == '1' and ',' not in self.edit_var.get(): pass else: value = '' initial_value = str(self.elements.item(self.rowid)['values'][int(self.column[-1])-1]) comma_flag = 0 div_flag = 0 for index in range(0,len(self.edit_var.get())): char = self.edit_var.get()[index] if char in '-0123456789.': value += char elif self.rowid[0] == 'n' and char == ',': if comma_flag == 1: self.edit_entry.destroy() self.active_edit_flag = 0 return value += char comma_flag = 1 comma_index = index if char == '/': if div_flag == 0: div_flag = 1 div_index = index elif div_flag == 1 and comma_flag == 1: div_flag = 2 div_index2 = index elif div_flag == 1 and comma_flag == 0 or div_flag == 2: self.edit_entry.destroy() self.active_edit_flag = 0 return if div_flag == 1: if comma_flag == 1: if div_index < comma_index: arg = int(float(value[:div_index])*100/float(value[div_index:comma_index-1]))/100.0 value = str(arg)+value[comma_index-1:] elif div_index > comma_index: arg = int(float(value[comma_index+1:div_index])*100/float(value[div_index:]))/100.0 value = value[:comma_index+1]+str(arg) else: arg = int(float(value[:div_index])*100/float(value[div_index:]))/100.0 value = str(arg) elif div_flag == 2: arg1 = int(float(value[:div_index])*100/float(value[div_index:comma_index-1]))/100.0 arg2 = int(float(value[comma_index:div_index2-1])*100/float(value[div_index2-1:]))/100.0 value = str(arg1)+','+str(arg2) if value == '' or value == initial_value: self.edit_entry.destroy() self.active_edit_flag = 0 return self.elements.set(self.rowid,column=(int(self.column[-1])-1),value=value) if self.mark_var.get() == 1: self.sel_point = [self.elements.item(self.rowid,"values")[1],self.elements.item(self.rowid,"values")[2]] self.graph_update() self.edit_entry.destroy() self.active_edit_flag = 0
def show(frame, iterator): """Выводит на экран выборку, заданную в iterator""" scrollbar = Scrollbar(frame) tree = Treeview(frame, selectmode='none', padding=3, style='Custom.Treeview', height=REPORT_HEIGHT, yscrollcommand=scrollbar.set) tree.pack(side=LEFT, fill=BOTH, expand=YES) scrollbar.config(command=tree.yview) scrollbar.pack(side=LEFT, fill=Y) tree.tag_configure('1', font=('Verdana', FONT_SIZE_REPORT)) tree.tag_configure('2', font=('Verdana', FONT_SIZE_REPORT), background='#f5f5ff') Style().configure('Custom.Treeview', rowheight=FONT_SIZE_REPORT*2) columns = ['#' + str(x + 1) for x in range(5)] tree.configure(columns=columns) for q in range(len(header)): tree.heading('#%d' % (q + 1), text=header[q], anchor='w') tree.column('#%d' % (q + 1), width=REPORT_SCALE * col_width[q + 1], anchor='w') tree.heading('#0', text='', anchor='w') tree.column('#0', width=0, anchor='w', minwidth=0) flag = True for item in iterator: col = [] col.append(add_s(item.reason.text)) col.append(add_s(item.summ)) col.append(add_s(item.comment)) col.append(add_s(item.date_time.strftime('%d.%m.%Y'))) col.append(add_s(item.date_time.time())[:8]) flag = not flag if flag: tree.insert('', 'end', text='', values=col, tag='2') else: tree.insert('', 'end', text='', values=col, tag='1')
class Display: def __init__(self, controller): self.controller = controller self.currIndex = 0 # initialize the GUI self.app = Tk() self.app.title('Jack Magee\'s Pub') self.tree = Treeview(self.app, height=30) # name the tree columns, not sure if they have to be named numbers but that's how the example did it self.tree["columns"]=("one", "two", "three", "four") # set the column widths self.tree.column("one", width=200) self.tree.column("two", width=300) self.tree.column("three", width=200) self.tree.column("four", width=200) # set the column headings self.tree.heading("#0", text= "ID") self.tree.heading("one", text="Name") self.tree.heading("two", text="Order") self.tree.heading("three", text="Price") self.tree.heading("four", text="Respond (double-click)") self.tree.pack() # register handler for double-clicks self.tree.bind("<Double-1>", self.OnDoubleClick) def mainloop(self): self.app.mainloop() # this is like making tree entries buttons def OnDoubleClick(self, event): # get the pressed item item = self.tree.selection()[0] # get the item's text response = self.tree.item(item,"text") # this is the only response we are sending for now if response == 'rdy': # get the parent directory whose text is the customer id parent = self.tree.parent(item) customer_id = self.tree.item(parent,"text") # remove it from the tree self.tree.delete(parent) # send the message to the customer self.controller.send_msg(customer_id, response) # add a new order to the tree def takeOrder(self, customer_id, name, order, price): # just a row identifier thisRow = str(self.currIndex) # insert the i.d. and name at the top level self.tree.insert("", self.currIndex, thisRow, text=customer_id, values=(name, "", "", "")) # insert the "button" for sending notification to clients self.tree.insert(thisRow, 0, text='rdy', values=("", "", "", "Ready For Pick Up")) # this is a hacky solution to get multiline orders to appear because treeviews will # crop anything more than 1 line so I just make a new entry for every line multiline_order = order.split('\n') this_line = 1 for line in multiline_order[:-1]: # exclude the last end line if this_line == 1: # the first line has the name of the order and it's price self.tree.insert(thisRow, 1, text="order",values=("", order, price, "")) else: # just keep printing the extra options, sides, and add ons self.tree.insert(thisRow, this_line, text="order",values=("", line, "", "")) this_line += 1 self.currIndex += 1
def initUI_main(self): self.parent.title("Personal Helper") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.columnconfigure(7, weight=1) self.columnconfigure(5, pad=10) self.columnconfigure(3, pad=10) self.columnconfigure(1, weight=3) self.rowconfigure(0, weight=0) self.rowconfigure(5, weight=1) self.rowconfigure(5, pad=7) self.rowconfigure(6, pad=6) lbl = Label(self, text="Windows") lbl.grid(sticky=W+N, pady=4, padx=5) check_box = {"work": IntVar(), "boost": IntVar()} check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"]) check1.grid(row=7, column=0) check2 = Checkbutton(self, text="boost games", variable=check_box["boost"]) check2.grid(row=7, column=1) ### old version, may be used again later area = Treeview(self) area['show'] = 'headings' area["columns"] = ("one", "two", "three", "four") area.column("one", width=10) area.column("two", width=10) area.column("three", width=10) area.column("four", width=10) area.heading("one", text="process name") area.heading("two", text="Priority") area.heading("three", text="PID") area.heading("four", text="Usage") ###about this part #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) ####### #comboboxes and relevant buttons self.block_drop = Combobox(self, postcommand= self.update_blocked) self.block_drop['values'] = working_bans self.block_drop.current(0) self.block_drop.grid(row=1, column=1, pady=1) self.entry = Entry(self) self.entry.insert(0, "enter to block") self.entry.grid(row=1, column=4) block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get())) block_btn_remv.grid(row=1, column=2) block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"])) block_btn_add.grid(row=1, column=3) ############ #boosted combo self.boost_drop = Combobox(self, postcommand=self.update_boosted) self.boost_drop['values'] = boosted self.boost_drop.current(0) self.boost_drop.grid(row=2, column=1, pady=1) self.entry2 = Entry(self) self.entry2.insert(0, "enter to buff priority") self.entry2.grid(row=2, column=4, pady=4) boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get())) boost_btn_remv.grid(row=2, column=2) boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"])) boost_btn_add.grid(row=2, column=3) ######################################### #degraded combo self.deg_drop = Combobox(self, postcommand=self.update_degraded) self.deg_drop['values'] = degraded self.deg_drop.current(0) self.deg_drop.grid(row=3, column=1, pady=1) self.entry3 = Entry(self) self.entry3.insert(0, "enter to lower priority") self.entry3.grid(row=3, column=4, pady=4) deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get())) deg_btn_remv.grid(row=3, column=2) deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"])) deg_btn_add.grid(row=3, column=3) #### #music combo self.music_drop = Combobox(self, postcommand=self.update_music) self.music_drop['values'] = music_list.keys() self.music_drop.current(0) self.music_drop.grid(row=4, column=1, pady=1) self.entry4 = Entry(self) self.entry4.insert(0, "enter url") self.entry4.grid(row=4, column=5) self.entry5 = Entry(self) self.entry5.insert(0, "enter song's name") self.entry5.grid(row=4, column=4) music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get())) music_btn_remv.grid(row=4, column=2) music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"])) music_btn_add.grid(row=4, column=3) abtn = Button(self, text="Activate", command=scan_computer_programs) abtn.grid(row=1, column=5, sticky=E) sbtn = Button(self, text="Stop", command=lambda: stop_running()) sbtn.grid(row=2, column=5, pady=6, sticky=E) cbtn = Button(self, text="Close", command=quit) cbtn.grid(row=3, column=5, pady=4, sticky=E) hbtn = Button(self, text="Save", command=save_lists) hbtn.grid(row=6, column=0, sticky=W) tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py")) tsbtn.grid(row=3, column=5, sticky=E) obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box)) obtn.grid(row=6, column=5, sticky=E)
def start_browse_payments(): global root root = Tk() root.title("Browse Payments") root.minsize(width=500, height=500) browse_payments_tree = Treeview(root) browse_payments_tree["columns"] = ("1", "2", "3", "4", "5", "6") browse_payments_tree.column("1", width=100) browse_payments_tree.column("2", width=100) browse_payments_tree.column("3", width=100) browse_payments_tree.column("4", width=100) browse_payments_tree.column("5", width=100) browse_payments_tree.column("6", width=100) browse_payments_tree.heading("1", text="Payment ID") browse_payments_tree.heading("2", text="Camper ID") browse_payments_tree.heading("3", text="Camp ID") browse_payments_tree.heading("4", text="Date of Payment") browse_payments_tree.heading("5", text="Amount Paid") browse_payments_tree.heading("6", text="Camp Start Date") index = 0 for payment_id in Payment.get_all_ids(): current_payment = Payment(payment_id[0]) data = current_payment.select_payment() mycamp = Camp(data[1]) camp_start = mycamp.select_camp()[0] browse_payments_tree.insert('', index, text="row" + str(index + 1), values=(payment_id, data[0], data[1], data[2], data[3], camp_start)) index += 1 browse_payments_tree.pack() exit_payments_camp_bt = Button(root, text="Exit", width=30, command=exit_browse_payment_bt_handler) exit_payments_camp_bt.pack(expand=True) root.mainloop()
def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True): self._stripped_rows = stripped_rows self._columns = columns self._number_of_rows = 0 self._number_of_columns = len(columns) self.row = self.List_Of_Rows(self) self.column = self.List_Of_Columns(self) s = Style() if style is None: style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index self._style_index += 1 else: style_name = style style_map = {} if selection_background is not None: style_map["background"] = [('selected', selection_background)] if selection_foreground is not None: style_map["foeground"] = [('selected', selection_foreground)] if style_map: s.map(style_name, **style_map) style_config = {} if cell_background is not None: style_config["background"] = cell_background if cell_foreground is not None: style_config["foreground"] = cell_foreground if cell_font is None: font_name = s.lookup(style_name, "font") cell_font = nametofont(font_name) else: if not isinstance(cell_font, Font): if isinstance(cell_font, basestring): cell_font = nametofont(cell_font) else: if len(font) == 1: cell_font = Font(family=cell_font[0]) elif len(font) == 2: cell_font = Font(family=cell_font[0], size=cell_font[1]) elif len(font) == 3: cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2]) else: raise ValueError("Not possible more than 3 values for font") style_config["font"] = cell_font self._cell_font = cell_font self._rowheight = cell_font.metrics("linespace")+cell_pady style_config["rowheight"]=self._rowheight if field_background is not None: style_config["fieldbackground"] = field_background s.configure(style_name, **style_config) heading_style_config = {} if heading_font is not None: heading_style_config["font"] = heading_font if heading_background is not None: heading_style_config["background"] = heading_background if heading_foreground is not None: heading_style_config["foreground"] = heading_foreground heading_style_name = style_name + ".Heading" s.configure(heading_style_name, **heading_style_config) treeview_kwargs = {"style": style_name} if height is not None: treeview_kwargs["height"] = height if padding is not None: treeview_kwargs["padding"] = padding if headers: treeview_kwargs["show"] = "headings" else: treeview_kwargs["show"] = "" if select_mode is not None: treeview_kwargs["selectmode"] = select_mode self.interior = Treeview(master, columns=columns, **treeview_kwargs) if command is not None: self._command = command self.interior.bind("<<TreeviewSelect>>", self._on_select) for i in range(0, self._number_of_columns): if sort: self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False)) else: self.interior.heading(i, text=columns[i], anchor=heading_anchor) if adjust_heading_to_content: self.interior.column(i, width=Font().measure(columns[i])) self.interior.column(i, anchor=cell_anchor) if data is not None: for row in data: self.insert_row(row)
class Multicolumn_Listbox(object): _style_index = 0 class List_Of_Rows(object): def __init__(self, multicolumn_listbox): self._multicolumn_listbox = multicolumn_listbox def data(self, index): return self._multicolumn_listbox.row_data(index) def get(self, index): return Row(self._multicolumn_listbox, index) def insert(self, data, index=None): self._multicolumn_listbox.insert_row(data, index) def delete(self, index): self._multicolumn_listbox.delete_row(index) def update(self, index, data): self._multicolumn_listbox.update_row(index, data) def select(self, index): self._multicolumn_listbox.select_row(index) def deselect(self, index): self._multicolumn_listbox.deselect_row(index) def set_selection(self, indices): self._multicolumn_listbox.set_selection(indices) def __getitem__(self, index): return self.get(index) def __setitem__(self, index, value): return self._multicolumn_listbox.update_row(index, value) def __delitem__(self, index): self._multicolumn_listbox.delete_row(index) def __len__(self): return self._multicolumn_listbox.number_of_rows class List_Of_Columns(object): def __init__(self, multicolumn_listbox): self._multicolumn_listbox = multicolumn_listbox def data(self, index): return self._multicolumn_listbox.get_column(index) def get(self, index): return Column(self._multicolumn_listbox, index) def delete(self, index): self._multicolumn_listbox.delete_column(index) def update(self, index, data): self._multicolumn_listbox.update_column(index, data) def __getitem__(self, index): return self.get(index) def __setitem__(self, index, value): return self._multicolumn_listbox.update_column(index, value) def __delitem__(self, index): self._multicolumn_listbox.delete_column(index) def __len__(self): return self._multicolumn_listbox.number_of_columns def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor=CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font=None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True): self._stripped_rows = stripped_rows self._columns = columns self._number_of_rows = 0 self._number_of_columns = len(columns) self.row = self.List_Of_Rows(self) self.column = self.List_Of_Columns(self) s = Style() if style is None: style_name = "Multicolumn_Listbox%s.Treeview" % self._style_index self._style_index += 1 else: style_name = style style_map = {} if selection_background is not None: style_map["background"] = [('selected', selection_background)] if selection_foreground is not None: style_map["foeground"] = [('selected', selection_foreground)] if style_map: s.map(style_name, **style_map) style_config = {} if cell_background is not None: style_config["background"] = cell_background if cell_foreground is not None: style_config["foreground"] = cell_foreground if cell_font is None: font_name = s.lookup(style_name, "font") cell_font = nametofont(font_name) else: if not isinstance(cell_font, Font): if isinstance(cell_font, basestring): cell_font = nametofont(cell_font) else: if len(font) == 1: cell_font = Font(family=cell_font[0]) elif len(font) == 2: cell_font = Font(family=cell_font[0], size=cell_font[1]) elif len(font) == 3: cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2]) else: raise ValueError( "Not possible more than 3 values for font") style_config["font"] = cell_font self._cell_font = cell_font self._rowheight = cell_font.metrics("linespace") + cell_pady style_config["rowheight"] = self._rowheight if field_background is not None: style_config["fieldbackground"] = field_background s.configure(style_name, **style_config) heading_style_config = {} if heading_font is not None: heading_style_config["font"] = heading_font if heading_background is not None: heading_style_config["background"] = heading_background if heading_foreground is not None: heading_style_config["foreground"] = heading_foreground heading_style_name = style_name + ".Heading" s.configure(heading_style_name, **heading_style_config) treeview_kwargs = {"style": style_name} if height is not None: treeview_kwargs["height"] = height if padding is not None: treeview_kwargs["padding"] = padding if headers: treeview_kwargs["show"] = "headings" else: treeview_kwargs["show"] = "" if select_mode is not None: treeview_kwargs["selectmode"] = select_mode self.interior = Treeview(master, columns=columns, **treeview_kwargs) if command is not None: self._command = command self.interior.bind("<<TreeviewSelect>>", self._on_select) for i in range(0, self._number_of_columns): if sort: self.interior.heading( i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False)) else: self.interior.heading(i, text=columns[i], anchor=heading_anchor) if adjust_heading_to_content: self.interior.column(i, width=Font().measure(columns[i])) self.interior.column(i, anchor=cell_anchor) if data is not None: for row in data: self.insert_row(row) @property def row_height(self): return self._rowheight @property def font(self): return self._cell_font def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None): kwargs = {} for config_name in ("width", "anchor", "stretch", "minwidth"): config_value = locals()[config_name] if config_value is not None: kwargs[config_name] = config_value self.interior.column('#%s' % (index + 1), **kwargs) def row_data(self, index): try: item_ID = self.interior.get_children()[index] except IndexError: raise ValueError("Row index out of range: %d" % index) return self.item_ID_to_row_data(item_ID) def update_row(self, index, data): try: item_ID = self.interior.get_children()[index] except IndexError: raise ValueError("Row index out of range: %d" % index) if len(data) == len(self._columns): self.interior.item(item_ID, values=data) else: raise ValueError("The multicolumn listbox has only %d columns" % self._number_of_columns) def delete_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d" % index) self.interior.delete(item_ID) self._number_of_rows -= 1 if self._stripped_rows: for i in range(index, self._number_of_rows): self.interior.tag_configure(list_of_items[i + 1], background=self._stripped_rows[i % 2]) def insert_row(self, data, index=None): if len(data) != self._number_of_columns: raise ValueError("The multicolumn listbox has only %d columns" % self._number_of_columns) if index is None: index = self._number_of_rows - 1 item_ID = self.interior.insert('', index, values=data) self.interior.item(item_ID, tags=item_ID) self._number_of_rows += 1 if self._stripped_rows: list_of_items = self.interior.get_children() self.interior.tag_configure(item_ID, background=self._stripped_rows[index % 2]) for i in range(index + 1, self._number_of_rows): self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i % 2]) def column_data(self, index): return [ self.interior.set(child_ID, index) for child_ID in self.interior.get_children('') ] def update_column(self, index, data): for i, item_ID in enumerate(self.interior.get_children()): data_row = self.item_ID_to_row_data(item_ID) data_row[index] = data[i] self.interior.item(item_ID, values=data_row) return data def clear(self): # Another possibility: # self.interior.delete(*self.interior.get_children()) for row in self.interior.get_children(): self.interior.delete(row) self._number_of_rows = 0 def update(self, data): self.clear() for row in data: self.insert_row(row) def focus(self, index=None): if index is None: return self.interior.item(self.interior.focus()) else: item = self.interior.get_children()[index] self.interior.focus(item) def state(self, state=None): if stateSpec is None: return self.interior.state() else: self.interior.state(state) @property def number_of_rows(self): return self._number_of_rows @property def number_of_columns(self): return self._number_of_columns def toogle_selection(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d" % index) self.interior.selection_toggle(item_ID) def select_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d" % index) self.interior.selection_add(item_ID) def deselect_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d" % index) self.interior.selection_remove(item_ID) def deselect_all(self): self.interior.selection_remove(self.interior.selection()) def set_selection(self, indices): list_of_items = self.interior.get_children() self.interior.selection_set(" ".join(list_of_items[row_index] for row_index in indices)) @property def selected_rows(self): data = [] for item_ID in self.interior.selection(): data_row = self.item_ID_to_row_data(item_ID) data.append(data_row) return data @property def indices_of_selected_rows(self): list_of_indices = [] for index, item_ID in enumerate(self.interior.get_children()): if item_ID in self.interior.selection(): list_of_indices.append(index) return list_of_indices def delete_all_selected_rows(self): selected_items = self.interior.selection() for item_ID in selected_items: self.interior.delete(item_ID) number_of_deleted_rows = len(selected_items) self._number_of_rows -= number_of_deleted_rows return number_of_deleted_rows def _on_select(self, event): for item_ID in event.widget.selection(): data_row = self.item_ID_to_row_data(item_ID) self._command(data_row) def item_ID_to_row_data(self, item_ID): item = self.interior.item(item_ID) return item["values"] @property def table_data(self): data = [] for item_ID in self.interior.get_children(): data_row = self.item_ID_to_row_data(item_ID) data.append(data_row) return data @table_data.setter def table_data(self, data): self.update(data) def cell_data(self, row, column): """Get the value of a table cell""" try: item = self.interior.get_children()[row] except IndexError: raise ValueError("Row index out of range: %d" % row) return self.interior.set(item, column) def update_cell(self, row, column, value): """Set the value of a table cell""" item_ID = self.interior.get_children()[row] data = self.item_ID_to_row_data(item_ID) data[column] = value self.interior.item(item_ID, values=data) def __getitem__(self, index): if isinstance(index, tuple): row, column = index return self.cell_data(row, column) else: raise Exception("Row and column indices are required") def __setitem__(self, index, value): if isinstance(index, tuple): row, column = index self.update_cell(row, column, value) else: raise Exception("Row and column indices are required") def bind(self, event, handler): self.interior.bind(event, handler) def sort_by(self, col, descending): """ sort tree contents when a column header is clicked """ # grab values to sort data = [(self.interior.set(child_ID, col), child_ID) for child_ID in self.interior.get_children('')] # if the Demo_programs to be sorted is numeric change to float try: data = [(float(number), child_ID) for number, child_ID in data] except ValueError: pass # now sort the Demo_programs in place data.sort(reverse=descending) for idx, item in enumerate(data): self.interior.move(item[1], '', idx) # switch the heading so that it will sort in the opposite direction self.interior.heading( col, command=lambda col=col: self.sort_by(col, not descending)) if self._stripped_rows: list_of_items = self.interior.get_children('') for i in range(len(list_of_items)): self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i % 2]) def destroy(self): self.interior.destroy() def item_ID(self, index): return self.interior.get_children()[index]
def __init__(self, master, xml=None, heading_text=None, heading_anchor=None, padding=None, cursor=None, takefocus=None, style=None): Frame.__init__(self, master, class_="XML_Viwer") self._vsb = Scrollbar(self, orient=VERTICAL) self._hsb = Scrollbar(self, orient=HORIZONTAL) kwargs = {} kwargs["yscrollcommand"] = lambda f, l: autoscroll(self._vsb, f, l) kwargs["xscrollcommand"] = lambda f, l: autoscroll(self._hsb, f, l) if style is not None: kwargs["style"] = style if padding is not None: kwargs["padding"] = padding if cursor is not None: kwargs["cursor"] = cursor if takefocus is not None: kwargs["takefocus"] = takefocus self._treeview = Treeview(self, **kwargs) if heading_text is not None: if heading_anchor is not None: self._treeview.heading("#0", text=heading_text, anchor=heading_anchor) else: self._treeview.heading("#0", text=heading_text) self._treeview.bind("<<TreeviewOpen>>", self._on_open) self._treeview.bind("<<TreeviewClose>>", self._on_close) # Without this line, horizontal scrolling doesn't work properly. self._treeview.column("#0", stretch=False) self._vsb['command'] = self._treeview.yview self._hsb['command'] = self._treeview.xview self._treeview.grid(column=0, row=0, sticky=N + S + W + E) self._vsb.grid(column=1, row=0, sticky=N + S) self._hsb.grid(column=0, row=1, sticky=E + W) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._element_tree = None self._item_ID_to_element = {} if xml is not None: self.parse_xml(xml)
def __init__(self, parent, controller): Frame.__init__(self, parent) lupa = PhotoImage(file='img/lupa.png') #VARIABLES tcontrato = ['Vivienda', 'Comercial'] aplica = StringVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="RECIBO DE CAJA", font="bold") self.header.pack(pady=20, side=TOP) #========================== WRAPPER ========================== self.wrapper = Frame (self) self.wrapper.pack(side=TOP, fill=Y) #self.wrapper.pack(side=LEFT, fill=Y)#Este ubica el forma a la IZA #================ NOTEBOOK =============> self.nb = Notebook(self.wrapper) #-----------------------> TAB 1 self.tab1 = Frame (self.nb) self.tab1.pack() self.f0 = Frame(self.tab1)#------------------------------------- self.f0.pack(pady=5,fill=X) self.R1 = Radiobutton(self.f0, text="Arrendatario", variable=aplica, value='Arrendatario') self.R1.pack(padx=20,side=LEFT) self.R2 = Radiobutton (self.f0, text="Propietario", variable=aplica, value='Propietario') self.R2.pack(padx=20,side=LEFT) self.R3 = Radiobutton (self.f0, text="Tercero", variable=aplica, value='Tercero') self.R3.pack(padx=20,side=LEFT) self.f1 = Frame(self.tab1)#------------------------------------- self.f1.pack(pady=5,fill=X) self.cc = Label(self.f1, text='CC/Nit: ') self.cc.pack(side=LEFT) self.ccE = Entry(self.f1) self.ccE.pack(side=LEFT) self.b1 = Button(self.f1, text='Buscar', image=lupa) self.b1.image=lupa self.b1.pack(side=LEFT) self.f2 = Frame(self.tab1) self.f2.pack(pady=5,fill=X)#------------------------------------ self.nombre = Label(self.f2, text='Nombre:') self.nombre.pack(side=LEFT) self.nombrE = Entry(self.f2, width=5, state=DISABLED) self.nombrE.pack(side=LEFT, fill=X, expand=1) self.f3 = Frame(self.tab1) self.f3.pack(pady=5,fill=X)#------------------------------------ self.inmueble = Label(self.f3, text='Inmueble:') self.inmueble.pack(side=LEFT) self.inmuebleCbx = Combobox(self.f3, values=NONE, width=10) self.inmuebleCbx.set('') self.inmuebleCbx.pack(side=LEFT, fill=X, expand=1) self.b2 = Button(self.f3, text='Agregar', image=lupa) self.b2.image=lupa self.b2.pack(side=LEFT) self.f4 = Frame(self.tab1) self.f4.pack(pady=5,fill=X)#------------------------------------ self.fpago = Label(self.f4, text='Forma de Pago:') self.fpago.pack(side=LEFT) self.fpagoCbx = Combobox(self.f4, values=NONE, width=10) self.fpagoCbx.set('') self.fpagoCbx.pack(side=LEFT) self.b3 = Button(self.f4, text='Crear novedad', state=DISABLED) self.b3.pack(side=LEFT) #========================== TREEVIEW =========================== self.f5 = Frame(self.tab1) self.f5.pack(pady=5,fill=X)#------------------------------------ self.tree = Treeview(self.f5, height=4, show="headings", columns=('col1','col2','col3')) self.tree.pack(side=LEFT, fill=X, expand=1) self.tree.column('col1', width=20, anchor='center') self.tree.column('col2', width=200, anchor='center') self.tree.column('col3', width=10, anchor='center') self.tree.heading('col1', text='CC') self.tree.heading('col2', text='Descripción') self.tree.heading('col3', text='Valor') self.scroll = Scrollbar(self.f3,orient=VERTICAL,command=self.tree.yview) self.tree.configure(yscrollcommand=self.scroll.set) self.f6 = Frame(self.tab1) self.f6.pack(pady=5,fill=X)#-------------------- self.notesL = Label(self.f6, text='Observaciones:') self.notesL.pack(side=LEFT) self.f7 = Frame(self.tab1) self.f7.pack(pady=5,fill=X)#------------------- self.notesT = Text(self.f7, height=5) self.notesT.pack(fill=X, side=LEFT, expand=1) #-----------------------> TAB 2 self.tab2 = Frame (self.nb) self.tab2.pack() #-----------------------> TAB 3 self.tab3 = Frame (self.nb) self.tab3.pack() #--------------------------------------------------------------- self.nb.add (self.tab1, text="Datos Generales") self.nb.add(self.tab2, text="Referencia de Pago", state=DISABLED) self.nb.add(self.tab3, text="Referencias Bancarias", state=DISABLED) self.nb.pack() #--------------------------------------------------------------- self.fBtn = Frame(self.wrapper) self.fBtn.pack()#------------------------------- self.queryB = Button(self.fBtn, text='Consultar') self.queryB.pack(side=RIGHT) self.deleteB = Button(self.fBtn, text='Borrar') self.deleteB.pack(side=RIGHT) self.updateB = Button(self.fBtn, text='Actualizar') self.updateB.pack(side=RIGHT) self.addB = Button(self.fBtn, text='Agregar') self.addB.pack(side=RIGHT) #========================= ASIDE =========================== """
def CreateUI(self): tv = Treeview(self) tv['columns'] = ('no_of_coin', 's_id', 'm_s_id') tv.heading("#0", text='Date', anchor='c') tv.column("#0", anchor="c") tv.heading('no_of_coin', text='No Of Coin') tv.column('no_of_coin', anchor='center', width=100) tv.heading('s_id', text='Service ID') tv.column('s_id', anchor='center', width=100) tv.heading('m_s_id', text='Miner ID') tv.column('m_s_id', anchor='center', width=100) tv.grid(sticky=(N, S, W, E)) self.treeview = tv self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) btn = Button(self, text=('Back'), command=self.back, width=10, background='red') btn.grid(sticky=(S + E))
def __init__(self, parent, controller): Frame.__init__(self, parent) global docID, nombre, refbanco, tree, busqueda, info, delete global e3 lupa = PhotoImage(file='img/lupa.png') docID = StringVar() nombre = StringVar() refbanco = StringVar() busqueda = StringVar() info = IntVar() #WIDGETS #=========================== HEADER ============================ l0 = Label(self, text="BENEFICIARIOS", font="bold") l0.pack(pady=20, side=TOP) #=========================== WRAPPER =========================== wrapper = Frame (self) wrapper.pack(side=TOP, fill=Y) #wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ f1 = Frame(wrapper) f1.pack(pady=5, fill=X)#----------------------------------- l1 = Label (f1, text="CC/Nit: ") l1.pack(side=LEFT) e1 = Entry (f1, textvariable=docID, width=20) e1.pack(side=LEFT) e1.bind("<KeyRelease>", caps) e1.focus_set() f2 = Frame(wrapper) f2.pack(pady=5, fill=X)#----------------------------------- l2 = Label (f2, text="Nombre: ") l2.pack(side=LEFT) e2 = Entry (f2, textvariable=nombre, width=60) e2.pack(side=LEFT, fill=X, expand=1) e2.bind("<KeyRelease>", caps) f3 = Frame(wrapper) f3.pack(pady=5, fill=X)#----------------------------------- l3 = Label (f3, text="Referencia Bancaria: ") l3.pack(side=LEFT) e3 = Entry (f3, textvariable=refbanco, width=60) e3.pack(side=LEFT, fill=X, expand=1) e3.bind("<KeyRelease>", caps) f4 = Frame(wrapper) f4.pack(pady=5, fill=X)#----------------------------------- b1 = Button (f4, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar) b1.pack(side=RIGHT) b2 = Button (f4, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar) b2.pack(side=RIGHT) #========================== TREEVIEW =========================== f5 = Frame(wrapper) f5.pack(pady=5, fill=X)#----------------------------------- tree = Treeview(f5, show="headings", columns=('col1','col2')) tree.pack(side=LEFT, fill=X, expand=1) tree.column('col1', width=0, anchor='center') tree.column('col2', width=150, anchor='w') tree.heading('col1', text='CC/Nit') tree.heading('col2', text='Nombre Completo') scroll = Scrollbar(f5,orient=VERTICAL,command=tree.yview) tree.configure(yscrollcommand=scroll.set) f6 = Frame(wrapper) f6.pack(pady=5, fill=X)#----------------------------------- delete = Button (f6, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(side=RIGHT) e4 = Entry(f6, textvariable=busqueda) e4.pack(side=LEFT) e4.bind("<KeyRelease>", caps) b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar) b4.image = lupa b4.pack(side=LEFT) R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton (f6, text="Nombre", variable=info, value=2) R2.pack(side=LEFT) info.set(1)
class Multicolumn_Listbox(object): _style_index = 0 class List_Of_Rows(object): def __init__(self, multicolumn_listbox): self._multicolumn_listbox = multicolumn_listbox def data(self, index): return self._multicolumn_listbox.row_data(index) def get(self, index): return Row(self._multicolumn_listbox, index) def insert(self, data, index=None): self._multicolumn_listbox.insert_row(data, index) def delete(self, index): self._multicolumn_listbox.delete_row(index) def update(self, index, data): self._multicolumn_listbox.update_row(index, data) def select(self, index): self._multicolumn_listbox.select_row(index) def deselect(self, index): self._multicolumn_listbox.deselect_row(index) def set_selection(self, indices): self._multicolumn_listbox.set_selection(indices) def __getitem__(self, index): return self.get(index) def __setitem__(self, index, value): return self._multicolumn_listbox.update_row(index, value) def __delitem__(self, index): self._multicolumn_listbox.delete_row(index) def __len__(self): return self._multicolumn_listbox.number_of_rows class List_Of_Columns(object): def __init__(self, multicolumn_listbox): self._multicolumn_listbox = multicolumn_listbox def data(self, index): return self._multicolumn_listbox.get_column(index) def get(self, index): return Column(self._multicolumn_listbox, index) def delete(self, index): self._multicolumn_listbox.delete_column(index) def update(self, index, data): self._multicolumn_listbox.update_column(index, data) def __getitem__(self, index): return self.get(index) def __setitem__(self, index, value): return self._multicolumn_listbox.update_column(index, value) def __delitem__(self, index): self._multicolumn_listbox.delete_column(index) def __len__(self): return self._multicolumn_listbox.number_of_columns def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True): self._stripped_rows = stripped_rows self._columns = columns self._number_of_rows = 0 self._number_of_columns = len(columns) self.row = self.List_Of_Rows(self) self.column = self.List_Of_Columns(self) s = Style() if style is None: style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index self._style_index += 1 else: style_name = style style_map = {} if selection_background is not None: style_map["background"] = [('selected', selection_background)] if selection_foreground is not None: style_map["foeground"] = [('selected', selection_foreground)] if style_map: s.map(style_name, **style_map) style_config = {} if cell_background is not None: style_config["background"] = cell_background if cell_foreground is not None: style_config["foreground"] = cell_foreground if cell_font is None: font_name = s.lookup(style_name, "font") cell_font = nametofont(font_name) else: if not isinstance(cell_font, Font): if isinstance(cell_font, basestring): cell_font = nametofont(cell_font) else: if len(font) == 1: cell_font = Font(family=cell_font[0]) elif len(font) == 2: cell_font = Font(family=cell_font[0], size=cell_font[1]) elif len(font) == 3: cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2]) else: raise ValueError("Not possible more than 3 values for font") style_config["font"] = cell_font self._cell_font = cell_font self._rowheight = cell_font.metrics("linespace")+cell_pady style_config["rowheight"]=self._rowheight if field_background is not None: style_config["fieldbackground"] = field_background s.configure(style_name, **style_config) heading_style_config = {} if heading_font is not None: heading_style_config["font"] = heading_font if heading_background is not None: heading_style_config["background"] = heading_background if heading_foreground is not None: heading_style_config["foreground"] = heading_foreground heading_style_name = style_name + ".Heading" s.configure(heading_style_name, **heading_style_config) treeview_kwargs = {"style": style_name} if height is not None: treeview_kwargs["height"] = height if padding is not None: treeview_kwargs["padding"] = padding if headers: treeview_kwargs["show"] = "headings" else: treeview_kwargs["show"] = "" if select_mode is not None: treeview_kwargs["selectmode"] = select_mode self.interior = Treeview(master, columns=columns, **treeview_kwargs) if command is not None: self._command = command self.interior.bind("<<TreeviewSelect>>", self._on_select) for i in range(0, self._number_of_columns): if sort: self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False)) else: self.interior.heading(i, text=columns[i], anchor=heading_anchor) if adjust_heading_to_content: self.interior.column(i, width=Font().measure(columns[i])) self.interior.column(i, anchor=cell_anchor) if data is not None: for row in data: self.insert_row(row) @property def row_height(self): return self._rowheight @property def font(self): return self._cell_font def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None): kwargs = {} for config_name in ("width", "anchor", "stretch", "minwidth"): config_value = locals()[config_name] if config_value is not None: kwargs[config_name] = config_value self.interior.column('#%s'%(index+1), **kwargs) def row_data(self, index): try: item_ID = self.interior.get_children()[index] except IndexError: raise ValueError("Row index out of range: %d"%index) return self.item_ID_to_row_data(item_ID) def update_row(self, index, data): try: item_ID = self.interior.get_children()[index] except IndexError: raise ValueError("Row index out of range: %d"%index) if len(data) == len(self._columns): self.interior.item(item_ID, values=data) else: raise ValueError("The multicolumn listbox has only %d columns"%self._number_of_columns) def delete_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d"%index) self.interior.delete(item_ID) self._number_of_rows -= 1 if self._stripped_rows: for i in range(index, self._number_of_rows): self.interior.tag_configure(list_of_items[i+1], background=self._stripped_rows[i%2]) def insert_row(self, data, index=None): if len(data) != self._number_of_columns: raise ValueError("The multicolumn listbox has only %d columns"%self._number_of_columns) if index is None: index = self._number_of_rows-1 item_ID = self.interior.insert('', index, values=data) self.interior.item(item_ID, tags=item_ID) self._number_of_rows += 1 if self._stripped_rows: list_of_items = self.interior.get_children() self.interior.tag_configure(item_ID, background=self._stripped_rows[index%2]) for i in range(index+1, self._number_of_rows): self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i%2]) def column_data(self, index): return [self.interior.set(child_ID, index) for child_ID in self.interior.get_children('')] def update_column(self, index, data): for i, item_ID in enumerate(self.interior.get_children()): data_row = self.item_ID_to_row_data(item_ID) data_row[index] = data[i] self.interior.item(item_ID, values=data_row) return data def clear(self): # Another possibility: # self.interior.delete(*self.interior.get_children()) for row in self.interior.get_children(): self.interior.delete(row) self._number_of_rows = 0 def update(self, data): self.clear() for row in data: self.insert_row(row) def focus(self, index=None): if index is None: return self.interior.item(self.interior.focus()) else: item = self.interior.get_children()[index] self.interior.focus(item) def state(self, state=None): if stateSpec is None: return self.interior.state() else: self.interior.state(state) @property def number_of_rows(self): return self._number_of_rows @property def number_of_columns(self): return self._number_of_columns def toogle_selection(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d"%index) self.interior.selection_toggle(item_ID) def select_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d"%index) self.interior.selection_add(item_ID) def deselect_row(self, index): list_of_items = self.interior.get_children() try: item_ID = list_of_items[index] except IndexError: raise ValueError("Row index out of range: %d"%index) self.interior.selection_remove(item_ID) def deselect_all(self): self.interior.selection_remove(self.interior.selection()) def set_selection(self, indices): list_of_items = self.interior.get_children() self.interior.selection_set(" ".join(list_of_items[row_index] for row_index in indices)) @property def selected_rows(self): data = [] for item_ID in self.interior.selection(): data_row = self.item_ID_to_row_data(item_ID) data.append(data_row) return data @property def indices_of_selected_rows(self): list_of_indices = [] for index, item_ID in enumerate(self.interior.get_children()): if item_ID in self.interior.selection(): list_of_indices.append(index) return list_of_indices def delete_all_selected_rows(self): selected_items = self.interior.selection() for item_ID in selected_items: self.interior.delete(item_ID) number_of_deleted_rows = len(selected_items) self._number_of_rows -= number_of_deleted_rows return number_of_deleted_rows def _on_select(self, event): for item_ID in event.widget.selection(): data_row = self.item_ID_to_row_data(item_ID) self._command(data_row) def item_ID_to_row_data(self, item_ID): item = self.interior.item(item_ID) return item["values"] @property def table_data(self): data = [] for item_ID in self.interior.get_children(): data_row = self.item_ID_to_row_data(item_ID) data.append(data_row) return data @table_data.setter def table_data(self, data): self.update(data) def cell_data(self, row, column): """Get the value of a table cell""" try: item = self.interior.get_children()[row] except IndexError: raise ValueError("Row index out of range: %d"%row) return self.interior.set(item, column) def update_cell(self, row, column, value): """Set the value of a table cell""" item_ID = self.interior.get_children()[row] data = self.item_ID_to_row_data(item_ID) data[column] = value self.interior.item(item_ID, values=data) def __getitem__(self, index): if isinstance(index, tuple): row, column = index return self.cell_data(row, column) else: raise Exception("Row and column indices are required") def __setitem__(self, index, value): if isinstance(index, tuple): row, column = index self.update_cell(row, column, value) else: raise Exception("Row and column indices are required") def bind(self, event, handler): self.interior.bind(event, handler) def sort_by(self, col, descending): """ sort tree contents when a column header is clicked """ # grab values to sort data = [(self.interior.set(child_ID, col), child_ID) for child_ID in self.interior.get_children('')] # if the data to be sorted is numeric change to float try: data = [(float(number), child_ID) for number, child_ID in data] except ValueError: pass # now sort the data in place data.sort(reverse=descending) for idx, item in enumerate(data): self.interior.move(item[1], '', idx) # switch the heading so that it will sort in the opposite direction self.interior.heading(col, command=lambda col=col: self.sort_by(col, not descending)) if self._stripped_rows: list_of_items = self.interior.get_children('') for i in range(len(list_of_items)): self.interior.tag_configure(list_of_items[i], background=self._stripped_rows[i%2]) def destroy(self): self.interior.destroy() def item_ID(self, index): return self.interior.get_children()[index]
class XML_Viwer(Frame): def __init__(self, master, xml=None, heading_text=None, heading_anchor=None, padding=None, cursor=None, takefocus=None, style=None): Frame.__init__(self, master, class_="XML_Viwer") self._vsb = Scrollbar(self, orient=VERTICAL) self._hsb = Scrollbar(self, orient=HORIZONTAL) kwargs = {} kwargs["yscrollcommand"] = lambda f, l: autoscroll(self._vsb, f, l) kwargs["xscrollcommand"] = lambda f, l: autoscroll(self._hsb, f, l) if style is not None: kwargs["style"] = style if padding is not None: kwargs["padding"] = padding if cursor is not None: kwargs["cursor"] = cursor if takefocus is not None: kwargs["takefocus"] = takefocus self._treeview = Treeview(self, **kwargs) if heading_text is not None: if heading_anchor is not None: self._treeview.heading("#0", text=heading_text, anchor=heading_anchor) else: self._treeview.heading("#0", text=heading_text) self._treeview.bind("<<TreeviewOpen>>", self._on_open) self._treeview.bind("<<TreeviewClose>>", self._on_close) # Without this line, horizontal scrolling doesn't work properly. self._treeview.column("#0", stretch=False) self._vsb['command'] = self._treeview.yview self._hsb['command'] = self._treeview.xview self._treeview.grid(column=0, row=0, sticky=N + S + W + E) self._vsb.grid(column=1, row=0, sticky=N + S) self._hsb.grid(column=0, row=1, sticky=E + W) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._element_tree = None self._item_ID_to_element = {} if xml is not None: self.parse_xml(xml) def _on_open(self, event): item_ID = self._treeview.focus() if item_ID not in self._item_ID_to_element: return node = self._item_ID_to_element[item_ID] self._treeview.item(item_ID, text=self._repr_of_openning_tag(node)) def _on_close(self, event): item_ID = self._treeview.focus() if item_ID not in self._item_ID_to_element: return node = self._item_ID_to_element[item_ID] text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag( node) self._treeview.item(item_ID, text=text) def parse_xml(self, xml): self._element_tree = ET.ElementTree(ET.fromstring(xml)) self.clear() self._walk_xml(self._element_tree.getroot()) @property def element_tree(self): return self._element_tree @element_tree.setter def element_tree(self, element_tree): self._element_tree = element_tree self.clear() self._walk_xml(element_tree.getroot()) def clear(self): self._item_ID_to_element = {} self._treeview.delete(*self._treeview.get_children()) def _repr_of_openning_tag(self, node): text = "<" + node.tag attrs = node.attrib # list function is here necessary to provide support to Python 3 a_names = list(attrs.keys()) a_names.sort() for a_name in a_names: text += ' %s="' % a_name text += attrs[a_name] text += '"' text += ">" return text def _repr_of_closing_tag(self, node): return "</%s>" % node.tag def _walk_xml(self, node, depth=0, parent=""): text = self._repr_of_openning_tag(node) + self._repr_of_closing_tag( node) item = self._treeview.insert(parent, END, text=text) self._item_ID_to_element[item] = node if node.text: text = node.text.strip() if text != "": for line in text.splitlines(): self._treeview.insert(item, END, text=line) child_nodes = sorted(list(node), key=attrgetter('tag')) for child_node in node: self._walk_xml(child_node, depth + 1, parent=item) if node.tail: tail = node.tail.strip() if tail != "": for line in tail.splitlines(): self._treeview.insert(parent, END, text=line)
def _add_frames(self): # Adding Answer Backup Frame f1 = Frame(self) f1.grid(column=0, row=0, sticky="NWES") for i in range(4): f1.grid_rowconfigure(i, weight=0, pad=5) f1.grid_rowconfigure(4, weight=1, pad=5) for i in range(4): f1.grid_columnconfigure(i, weight=1, pad=5) Label(f1, anchor='e', text='Answers Count : ').grid(column=0, row=0, sticky='EWNS') self.answer_count = StringVar(value=len(self.crawler.answer_list)) Label(f1, anchor='w', textvariable=self.answer_count).grid(column=1, row=0, sticky='EWNS') Label(f1, anchor='e', text='User Name : ').grid(column=2, row=0, sticky='EWNS') self.user = StringVar(value='Unknown') Label(f1, anchor='w', textvariable=self.user).grid(column=3, row=0, sticky='EWNS') tf_col = '#e6e6e6' tf = Tkinter.Frame(f1, relief=GROOVE, borderwidth='2p') tf.grid(row=1, columnspan=2, column=0, sticky='EWNS') Label(tf, text='Quora User Options', bg=tf_col, anchor='c').grid(column=0, row=0, columnspan=2, sticky='EWNS') Button(tf, text='Login', command=lambda : self.thread('login'), highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS') Button(tf, text='Logout', command=lambda : self.thread('logout'), highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS') tf.grid_rowconfigure(0, weight=1, pad=5) tf.grid_rowconfigure(1, weight=1, pad=5) tf.grid_columnconfigure(0, weight=1, pad=5) tf.grid_columnconfigure(1, weight=1, pad=5) tf = Frame(f1, relief=GROOVE, borderwidth='2p') tf.grid(row=1, columnspan=2, column=2, sticky='EWNS') Label(tf, text='Answer List Option', bg=tf_col, anchor='c').grid(column=0, columnspan=2, row=0, sticky='EWNS') Button(tf, text='Reset', command=lambda : self.thread('reset'), highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS') Button(tf, text='Update', command=lambda : self.thread('update'), highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS') tf.grid_rowconfigure(0, weight=1, pad=5) tf.grid_rowconfigure(1, weight=1, pad=5) tf.grid_columnconfigure(0, weight=1, pad=5) tf.grid_columnconfigure(1, weight=1, pad=5) # Add Progress Bar self.backup_progress = Progressbar(f1, orient="horizontal", length=100, mode="determinate") self.backup_progress.grid(row=2, columnspan=4, column=0, sticky='EWNS') # Adding Status Pane self.backup_status = StringVar(value='Ready') Label(f1, textvariable=self.backup_status, anchor='w').grid(row=3, column=0, columnspan=4, sticky='EWNS') # Adding The list of all answers tree = Treeview(f1, columns=('sno', 'date', 'question')) tree.heading('sno', text='S. No') tree.heading('date', text='Date') tree.heading('question', text='Question') tree.column("#0", width=0, stretch=False) tree.column('sno', width=40, stretch=False, anchor='center') tree.column('date', width=120, stretch=False, anchor='center') tree.column('question', stretch=True, anchor='w') tree.grid(column=0, columnspan=4, row=4, sticky='EWNS') tree.bind("<Double-1>", self.tree_item_click) self.answer_tree = tree self.populate_tree() f2 = Frame(self) self.add(f1, text='Answer Backup', underline=7) self.add(f2, text='Analytics')
def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor=CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font=None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True): self._stripped_rows = stripped_rows self._columns = columns self._number_of_rows = 0 self._number_of_columns = len(columns) self.row = self.List_Of_Rows(self) self.column = self.List_Of_Columns(self) s = Style() if style is None: style_name = "Multicolumn_Listbox%s.Treeview" % self._style_index self._style_index += 1 else: style_name = style style_map = {} if selection_background is not None: style_map["background"] = [('selected', selection_background)] if selection_foreground is not None: style_map["foeground"] = [('selected', selection_foreground)] if style_map: s.map(style_name, **style_map) style_config = {} if cell_background is not None: style_config["background"] = cell_background if cell_foreground is not None: style_config["foreground"] = cell_foreground if cell_font is None: font_name = s.lookup(style_name, "font") cell_font = nametofont(font_name) else: if not isinstance(cell_font, Font): if isinstance(cell_font, basestring): cell_font = nametofont(cell_font) else: if len(font) == 1: cell_font = Font(family=cell_font[0]) elif len(font) == 2: cell_font = Font(family=cell_font[0], size=cell_font[1]) elif len(font) == 3: cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2]) else: raise ValueError( "Not possible more than 3 values for font") style_config["font"] = cell_font self._cell_font = cell_font self._rowheight = cell_font.metrics("linespace") + cell_pady style_config["rowheight"] = self._rowheight if field_background is not None: style_config["fieldbackground"] = field_background s.configure(style_name, **style_config) heading_style_config = {} if heading_font is not None: heading_style_config["font"] = heading_font if heading_background is not None: heading_style_config["background"] = heading_background if heading_foreground is not None: heading_style_config["foreground"] = heading_foreground heading_style_name = style_name + ".Heading" s.configure(heading_style_name, **heading_style_config) treeview_kwargs = {"style": style_name} if height is not None: treeview_kwargs["height"] = height if padding is not None: treeview_kwargs["padding"] = padding if headers: treeview_kwargs["show"] = "headings" else: treeview_kwargs["show"] = "" if select_mode is not None: treeview_kwargs["selectmode"] = select_mode self.interior = Treeview(master, columns=columns, **treeview_kwargs) if command is not None: self._command = command self.interior.bind("<<TreeviewSelect>>", self._on_select) for i in range(0, self._number_of_columns): if sort: self.interior.heading( i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False)) else: self.interior.heading(i, text=columns[i], anchor=heading_anchor) if adjust_heading_to_content: self.interior.column(i, width=Font().measure(columns[i])) self.interior.column(i, anchor=cell_anchor) if data is not None: for row in data: self.insert_row(row)
def __init__(self, parent, controller): Frame.__init__(self, parent) global docID, nombre, refbanco, tree, busqueda, info, delete global e3 lupa = PhotoImage(file='img/lupa.png') docID = StringVar() nombre = StringVar() refbanco = StringVar() busqueda = StringVar() info = IntVar() #WIDGETS #=========================== HEADER ============================ l0 = Label(self, text="BENEFICIARIOS", font="bold") l0.pack(pady=20, side=TOP) #=========================== WRAPPER =========================== wrapper = Frame(self) wrapper.pack(side=TOP, fill=Y) #wrapper.pack(side=LEFT, fill=Y) #UBICA EL FORM A LA IZQ f1 = Frame(wrapper) f1.pack(pady=5, fill=X) #----------------------------------- l1 = Label(f1, text="CC/Nit: ") l1.pack(side=LEFT) e1 = Entry(f1, textvariable=docID, width=20) e1.pack(side=LEFT) e1.bind("<KeyRelease>", caps) e1.focus_set() f2 = Frame(wrapper) f2.pack(pady=5, fill=X) #----------------------------------- l2 = Label(f2, text="Nombre: ") l2.pack(side=LEFT) e2 = Entry(f2, textvariable=nombre, width=60) e2.pack(side=LEFT, fill=X, expand=1) e2.bind("<KeyRelease>", caps) f3 = Frame(wrapper) f3.pack(pady=5, fill=X) #----------------------------------- l3 = Label(f3, text="Referencia Bancaria: ") l3.pack(side=LEFT) e3 = Entry(f3, textvariable=refbanco, width=60) e3.pack(side=LEFT, fill=X, expand=1) e3.bind("<KeyRelease>", caps) f4 = Frame(wrapper) f4.pack(pady=5, fill=X) #----------------------------------- b1 = Button(f4, text="Cargar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar) b1.pack(side=RIGHT) b2 = Button(f4, text="Agregar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=agregar) b2.pack(side=RIGHT) #========================== TREEVIEW =========================== f5 = Frame(wrapper) f5.pack(pady=5, fill=X) #----------------------------------- tree = Treeview(f5, show="headings", columns=('col1', 'col2')) tree.pack(side=LEFT, fill=X, expand=1) tree.column('col1', width=0, anchor='center') tree.column('col2', width=150, anchor='w') tree.heading('col1', text='CC/Nit') tree.heading('col2', text='Nombre Completo') scroll = Scrollbar(f5, orient=VERTICAL, command=tree.yview) tree.configure(yscrollcommand=scroll.set) f6 = Frame(wrapper) f6.pack(pady=5, fill=X) #----------------------------------- delete = Button(f6, text="Eliminar", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) delete.pack(side=RIGHT) e4 = Entry(f6, textvariable=busqueda) e4.pack(side=LEFT) e4.bind("<KeyRelease>", caps) b4 = Button(f6, text='BUSCAR', image=lupa, command=buscar) b4.image = lupa b4.pack(side=LEFT) R1 = Radiobutton(f6, text="CC/nit", variable=info, value=1) R1.pack(side=LEFT) R2 = Radiobutton(f6, text="Nombre", variable=info, value=2) R2.pack(side=LEFT) info.set(1)
def __init__(self, parent, controller): Frame.__init__(self, parent) global info, tree #VARIABLES info = IntVar() #WIDGETS #========================= HEADER =========================== self.header = Label(self, text="ADMINISTRADOR DE DOCUMENTOS", font="bold") self.header.pack(pady=20, side=TOP) #========================= WRAPPER 1 =========================== self.wrapper = Frame (self) self.wrapper.pack(side=LEFT, fill=Y) #======================== DOCUMENTOS DE ======================== self.f0 = Frame(self.wrapper) self.f0.pack(pady=5,fill=X)#------------------------------------ self.lf1 = LabelFrame(self.f0, text="Documentos de")#----------> self.f1 = Frame(self.lf1) self.f1.pack(pady=5, side=LEFT) self.pR1 = Radiobutton(self.f1, text="Propietario", variable=info, value=1, command=select) self.pR1.grid(row=0, column=0, sticky=W) self.aR2 = Radiobutton (self.f1, text="Arrendatario", variable=info, value=2, command=select) self.aR2.grid(row=1, column=0, sticky=W) self.tR3 = Radiobutton (self.f1, text="Tercero", variable=info, value=3, command=select) self.tR3.grid(row=2, column=0, sticky=W) self.lf1.pack(side=LEFT)#<-------------------------------------- #====================== FECHAS DE BÚSQUEDA ===================== self.lf2 = LabelFrame(self.f0, text="Fechas de búsqueda")#------> self.f2 = Frame(self.lf2) self.f2.pack(pady=5)#--------------------------- self.deL = Label(self.f2, text='De:') self.deL.pack(side=LEFT) self.deCbx = Combobox(self.f2, width=32) self.deCbx.set('') self.deCbx.pack(side=LEFT) self.f3 = Frame(self.lf2) self.f3.pack(pady=5)#--------------------------- self.hastaL = Label(self.f3, text='Hasta:') self.hastaL.pack(side=LEFT) self.hastaCbx = Combobox(self.f3, width=30) self.hastaCbx.set('') self.hastaCbx.pack(side=LEFT) self.lf2.pack(side=LEFT, fill=X)#<--------------------------- #========================= WRAPPER 2 =========================== self.wrapper2 = Frame (self.wrapper) self.wrapper2.pack(pady=5,fill=X) #========================= BENEFICIARIO ======================== self.box1 = Frame(self.wrapper2) self.box1.pack(side=LEFT) #--------------------------------------------------------------- self.f4 = Frame(self.box1) self.f4.pack() self.l1 = Label(self.f4, text="Beneficiario") self.l1.pack() tree = Treeview(self.f4, height=7, show="headings", columns=('col1','col2')) tree.pack(side=LEFT, fill=X, expand=1) tree.column('col1', width=100, anchor='center') tree.column('col2', width=180, anchor='center') tree.heading('col1', text='CC') tree.heading('col2', text='Nombres') self.scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview) tree.configure(yscrollcommand=self.scroll.set) self.f5 = Frame(self.box1)#---------------------------------- self.f5.pack() self.lf3 = LabelFrame(self.f5, text="Factura Propietario")#----> self.e1 = Entry(self.lf3, width=12).pack(side=LEFT) self.anularCk = Checkbutton(self.lf3, text="Anular").pack(side=LEFT) self.viewB = Button(self.lf3, text='Visualizar').pack(side=LEFT) self.lf3.pack(side=LEFT)#<-------------------------------------- #========================== FACTURAS ========================== self.box2 = Frame(self.wrapper2) self.box2.pack(side=LEFT) #--------------------------------------------------------------- self.f6 = Frame(self.box2) self.f6.pack() self.l2 = Label(self.f6, text="Facturas") self.l2.pack() self.tree = Treeview(self.f6, height=7, show="headings", columns=('col1','col2')) self.tree.pack(side=LEFT, fill=X, expand=1) self.tree.column('col1', width=100, anchor='center') self.tree.column('col2', width=100, anchor='center') self.tree.heading('col1', text='Número') self.tree.heading('col2', text='Valor') self.scroll = Scrollbar(self.f6,orient=VERTICAL,command=self.tree.yview) self.tree.configure(yscrollcommand=self.scroll.set) self.f7 = Frame(self.box2)#---------------------------------- self.f7.pack() self.lf4 = LabelFrame(self.f7, text="Factura Arrendatario")#----> self.e1 = Entry(self.lf4, width=12).pack(side=LEFT) self.anularCk = Checkbutton(self.lf4, text="Anular").pack(side=LEFT) self.viewB = Button(self.lf4, text='Ver', width=5).pack(side=LEFT) self.lf4.pack(side=LEFT)#<-------------------------------------- #========================== RECIBOS ========================== self.box3 = Frame(self.wrapper2) self.box3.pack(side=LEFT) #--------------------------------------------------------------- self.f8 = Frame(self.box3) self.f8.pack() self.l3 = Label(self.f8, text="Recibos de caja") self.l3.pack() self.tree = Treeview(self.f8, height=7, show="headings", columns=('col1','col2')) self.tree.pack(side=LEFT, fill=X, expand=1) self.tree.column('col1', width=100, anchor='center') self.tree.column('col2', width=100, anchor='center') self.tree.heading('col1', text='Número') self.tree.heading('col2', text='Valor') self.scroll = Scrollbar(self.f8,orient=VERTICAL,command=self.tree.yview) self.tree.configure(yscrollcommand=self.scroll.set) self.f9 = Frame(self.box3)#---------------------------------- self.f9.pack() self.lf5 = LabelFrame(self.f9, text="Recibos de caja")#----> self.e1 = Entry(self.lf5, width=12).pack(side=LEFT) self.anularCk = Checkbutton(self.lf5, text="Anular").pack(side=LEFT) self.viewB = Button(self.lf5, text='Ver', width=5).pack(side=LEFT) self.lf5.pack(side=LEFT)#<-------------------------------------- #===================== COMPROBANTE DE PAGO ===================== self.box4 = Frame(self.wrapper2) self.box4.pack(side=LEFT) #--------------------------------------------------------------- self.f10 = Frame(self.box4) self.f10.pack() self.l4 = Label(self.f10, text="Comprobantes de pago") self.l4.pack() self.tree = Treeview(self.f10, height=7, show="headings", columns=('col1','col2')) self.tree.pack(side=LEFT, fill=X, expand=1) self.tree.column('col1', width=100, anchor='center') self.tree.column('col2', width=100, anchor='center') self.tree.heading('col1', text='Número') self.tree.heading('col2', text='Valor') self.scroll = Scrollbar(self.f10,orient=VERTICAL,command=self.tree.yview) self.tree.configure(yscrollcommand=self.scroll.set) self.f11 = Frame(self.box4)#---------------------------------- self.f11.pack() self.lf6 = LabelFrame(self.f11, text="Pagos")#----> self.e1 = Entry(self.lf6, width=12).pack(side=LEFT) self.anularCk = Checkbutton(self.lf6, text="Anular").pack(side=LEFT) self.viewB = Button(self.lf6, text='Ver', width=5).pack(side=LEFT) self.lf6.pack(side=LEFT)#<--------------------------------------
class Tree(Treeview): """ Класс, формирующий таблицу """ def __init__(self, root, frame, num, logit, all_values, list_styles_names): Treeview.__init__(self, root) self.root = root self.num = num self.frame = frame self.name = "MOXA-%s" % str(self.num) self.tree = Treeview(frame, style=list_styles_names[num]) self.tree["columns"] = ("one", "two", "three") self.tree.heading("#0", text="") self.tree.column("#0", minwidth=0, width=5, stretch=NO) self.tree.heading("one", text="Port") self.tree.column("one", minwidth=0, width=30, stretch=NO) self.tree.column("two", minwidth=0, width=name_column, stretch=NO) self.tree.heading("three", text="State") self.tree.column("three", minwidth=0, width=state_column, stretch=YES) self.tree['height'] = 32 self.tree.tag_configure('green', background='gray7', foreground='green2') self.tree.tag_configure('red', background='gray7', foreground='tomato2') self.tree.tag_configure('blue', background='gray7', foreground='RoyalBlue') self.tree.tag_configure('yellow', background='gray7', foreground='yellow') self.tree.tag_configure('ready', background='gray7', foreground='white') self.tree.tag_configure( 'focus', background='yellow', ) self.tree.bind("<Motion>", self.mycallback) self.last_focus = None self.tree.pack(side=LEFT) self.logit = logit self.moxa = all_values[self.num][0] self.wraplength = 180 for key in self.moxa.keys(): self.tree.insert("", "end", values=(str(key), self.moxa[key], "<><><>"), tags=("green", )) def mycallback(self, event): """ Функция, отображающая комментарий при наведении мыши на канал """ _iid = self.tree.identify_row(event.y) if _iid != self.last_focus: if self.last_focus: try: if self.tw: self.tw.destroy() except: pass if _iid: row = self.tree.item(_iid) key = row["values"][0] if os.path.isfile('comments/comment_%s_%s.txt' % (self.num, key)): with open('comments/comment_%s_%s.txt' % (self.num, key), 'a+') as comment: file_log = comment.read() param = self.tree.bbox(_iid) x = (param[0] + space_X) * self.num y = param[1] + space_Y self.tw = tk.Toplevel() self.tw.wm_overrideredirect(True) self.tw.wm_geometry("+%d+%d" % (x, y)) label = tk.Label(self.tw, text=file_log, justify='left', background="yellow2", relief='solid', borderwidth=1, wraplength=self.wraplength, font=tkFont.Font(family=main_font, size=size_font)) label.pack() self.last_focus = _iid