def __bookmarks(self, master): panel = Frame(master) panel.grid_rowconfigure(0, weight=1) bookmarks = Frame(panel) bookmarks.grid_columnconfigure(0, weight=1) bookmarks.grid_rowconfigure(0, weight=1) li = Listbox(bookmarks, width=40) li.grid(column=0, row=0, sticky=(N, E, S, W)) self.bookmarks_list = li sb = Scrollbar(bookmarks, orient=VERTICAL, command=li.yview) sb.grid(column=1, row=0, sticky=(N, S)) li.config(yscrollcommand=sb.set) def _lbox_selected(*args): selected_idx = int(li.curselection()[0]) self.render_start.set(self.bookmarks_values[selected_idx]) self.canvas.xview_moveto(0) if not self.render_auto.get(): self.update() li.bind('<Double-Button-1>', _lbox_selected) bookmarks.grid(column=0, row=0, sticky=(N, E, S, W)) buttons = Frame(panel) Button(buttons, image=self.img_start, command=self.start_event).pack(side="left") Button(buttons, image=self.img_prev, command=self.prev_event).pack(side="left") Button(buttons, image=self.img_end, command=self.end_event).pack(side="right") Button(buttons, image=self.img_next, command=self.next_event).pack(side="right") buttons.grid(column=0, row=1, sticky=(E, W)) return panel
def __init__(self, parent, tile_size, grid_vm=None): Frame.__init__(self, parent, relief=RAISED, borderwidth=1) self.parent = parent self.tile_size = tile_size self.grid_vm = grid_vm self.columnconfigure(0, weight=1) self.columnconfigure(1, pad=3) self.rowconfigure(0, weight=1) self.rowconfigure(1, pad=3) hbar = Scrollbar(self, orient=HORIZONTAL) vbar = Scrollbar(self, orient=VERTICAL) canvas = Canvas(self, xscrollcommand=hbar.set, yscrollcommand=vbar.set) self.canvas = canvas self.lines = [] canvas.bind_all("<MouseWheel>", self._on_mousewheel_vertical) canvas.bind_all("<Shift-MouseWheel>", self._on_mousewheel_horizontal) # Set up scroll bars hbar.pack(side=BOTTOM, fill=X) hbar.config(command=canvas.xview) vbar.pack(side=RIGHT, fill=Y) vbar.config(command=canvas.yview) canvas.grid(column=0, row=0, sticky=N + W + E + S) hbar.grid(column=0, row=1, sticky=W + E) vbar.grid(column=1, row=0, sticky=N + S) if grid_vm: self.set_vm(grid_vm)
def setPixelList(self): if "pixelListBox" in self.widgetDict.keys(): pixelListBox = self.widgetDict["pixelListBox"] pixelListBox.delete(0, "end") self.widgetDict["kernelListbox"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) else: pixelListbox = Listbox(self) self.widgetDict["pixelListbox"] = pixelListbox scrollbar = Scrollbar(pixelListbox, orient="vertical") pixelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=pixelListbox.yview) self.widgetDict["pixelsLabel"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) pixelListbox.grid(row=3, column=2, rowspan=3, sticky="nsew") pixelListbox.columnconfigure(0, weight=1) pixelListbox.bind("<<ListboxSelect>>", self.updateActivePixel) scrollbar.grid(column=2, sticky="e") cobNumber = self.activeCob[:self.activeCob.index("_")] kernelNumber = self.activeKernel[self.activeKernel.index(" ") + 1:] kernel = self.RepLine.getKernel(int(cobNumber), int(kernelNumber)) for pixelNumber in xrange(len(kernel.keys())): pixelListbox.insert(pixelNumber, "Pixel: %s" % pixelNumber)
def createWidgets(self): "Create initial widget set." # Objects title = Label(self, text='Bandwidth (Gb/s)', bg=self.bg) width = self.gwidth height = self.gheight scale = self.createScale() graph = Canvas(self, width=width, height=height, background=self.bg) xbar = Scrollbar(self, orient='horizontal', command=graph.xview) ybar = Scrollbar(self, orient='vertical', command=self.yview) graph.configure(xscrollcommand=xbar.set, yscrollcommand=ybar.set, scrollregion=(0, 0, width, height)) scale.configure(yscrollcommand=ybar.set) # Layout title.grid(row=0, columnspan=3, sticky='new') scale.grid(row=1, column=0, sticky='nsew') graph.grid(row=1, column=1, sticky='nsew') ybar.grid(row=1, column=2, sticky='ns') xbar.grid(row=2, column=0, columnspan=2, sticky='ew') self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) return title, scale, graph
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 addScrollingFigure(figure, frame): global canvas, mplCanvas, interior, interior_id, cwid # set up a canvas with scrollbars canvas = Canvas(frame) canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW) xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL) yScrollbar = Scrollbar(frame) xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW) yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS) canvas.config(xscrollcommand=xScrollbar.set) xScrollbar.config(command=canvas.xview) canvas.config(yscrollcommand=yScrollbar.set) yScrollbar.config(command=canvas.yview) # plug in the figure figAgg = FigureCanvasTkAgg(figure, canvas) mplCanvas = figAgg.get_tk_widget() # and connect figure with scrolling region cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW) printBboxes("Init") changeSize(figure, 1)
def createCanvas( self ): "Create and return our scrolling canvas frame." f = Frame( self ) canvas = Canvas( f, width=self.cwidth, height=self.cheight, bg=self.bg ) # Scroll bars xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas
def startUI(self): self.parent.title("Testing") self.file_list = listdir(getcwd()) fileBox = Listbox(self.parent, selectmode=SINGLE) fileBox.pack() fileBox.grid(column=0, row=1, columnspan=3, rowspan=10, sticky=N + S) textBox = Text(self.parent) textBox.grid(column=4, row=0, columnspan=4, rowspan=10, sticky=N + S + E) ipBox = Entry(self.parent) ipBox.grid(column=0, row=0) btn = Button(text="Open ->", command=lambda: self.readFile(fileBox, textBox)) btn.grid(column=3, row=2) btnFire = Button(text="Fire away!", command=lambda: self.fireTorpedoes(ipBox, textBox)) btnFire.grid(column=3, row=3) scrlBar = Scrollbar(self.parent, command=textBox.yview) scrlBar.grid(column=8, row=0, rowspan=10, sticky=N + S) textBox.config(yscrollcommand=scrlBar.set) for i in self.file_list: fileBox.insert(END, i)
class Logger(LabelFrame): def __init__(self, root, *arg): LabelFrame.__init__(self, root, *arg, text="Log") self.log = Text(self, width=60, height=24, state=DISABLED, wrap=WORD, takefocus="0") self.log.grid(row=1, column=1, sticky=N+E+W+S) self.sblog = Scrollbar(self, command=self.log.yview, orient="vertical") self.sblog.grid(column=2, row=1, sticky=N+S+E) self.log.config(yscrollcommand=self.sblog.set) def logMsg(self, s): self.logMsgRaw(s+'\n') def logMsgRaw(self, s): self.log.config(state=NORMAL) self.log.insert(END, s) try: numlines = int(self.log.index("end - 1 line").split('.')[0]); except: numlines = 0 if numlines > MAXLINES: self.log.delete("1.0", "%d.0" % (numlines-MAXLINES)) self.log.config(state=DISABLED) self.log.see(END)
def __init__(self, master, mech): self.mech = mech frame = Frame(master) frame.grid() rct_label = Label(frame, text='Select Reactants') rct_label.grid(column=1, row=1) and_or = Label(frame, text='AND/OR') and_or.grid(column=3, row=1) prod_label = Label(frame, text='Select Products') prod_label.grid(column=4, row=1) what_to_do = Label(frame, text='Execute') what_to_do.grid(column=6, row=1) reactants_scrollbar = Scrollbar(frame, orient=VERTICAL) self.reactants = Listbox(frame, selectmode=EXTENDED, exportselection=0, yscrollcommand=reactants_scrollbar.set) self.reactants.grid(column=1, row=2) reactants_scrollbar.config(command=self.reactants.yview) reactants_scrollbar.grid(column=2, row=2, sticky=N + S) self.logical_and = IntVar() self.logical_and.set(1) c = Checkbutton(frame, text="AND", variable=self.logical_and) c.grid(column=3, row=2) products_scrollbar = Scrollbar(frame, orient=VERTICAL) self.products = Listbox(frame, selectmode=EXTENDED, exportselection=0) self.products.grid(column=4, row=2) products_scrollbar.config(command=self.products.yview) products_scrollbar.grid(column=5, row=2, sticky=N + S) self.method_list = Listbox(frame, selectmode=EXTENDED, exportselection=0) self.method_list.grid(column=6, row=2) #self.methods = [k for k in dir(self.mech) if k[:1] != '_' and isinstance(getattr(self.mech, k), MethodType)] self.methods = [ 'plot_rxns', 'find_rxns', 'print_rxns', 'print_irrs', 'print_net_rxn', 'plot_proc' ] method_labels = [ 'Plot Reactions', 'Show Rxn Ids', 'Print Rxns', 'Print IRRs', 'Print Net Rxn', 'Process Plot' ] for method in method_labels: self.method_list.insert(END, method) species_keys = self.mech.species_dict.keys() species_keys.sort() self.species_objects = [ self.mech.species_dict[spc] for spc in species_keys ] for spc in species_keys: self.reactants.insert(END, spc) self.products.insert(END, spc) self.execute_button = Button(frame, text="go", command=self.execute) self.execute_button.grid(column=6, row=4)
def __init__(self, filename, parentnotebook): """Create a new EditTab Argument filename -- name and path to the file being edited parentnotebook -- the NoteBook in which this tab will be added """ Frame.__init__(self) self._filename = filename self._parentnotebook = parentnotebook self._inputs = [] self.path = os.path.dirname(filename) self._dirty = False parentnotebook.add(self, state = 'normal') self._setLabel() #Set up GUI self.rowconfigure(0, weight = 1) self.columnconfigure(0, weight = 1) vscroll = Scrollbar(self, orient = VERTICAL) self._vscroll = vscroll vscroll.grid(row=0, column=1, sticky=N+S) hscroll = Scrollbar(self, orient = HORIZONTAL) self._hscroll = hscroll hscroll.grid(row=1, column=0, sticky=E+W) canvas = Canvas(self, yscrollcommand = vscroll.set, xscrollcommand = hscroll.set) self._canvas = canvas canvas.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = NSEW) vscroll['command'] = canvas.yview hscroll['command'] = canvas.xview scrollframe = Frame(canvas) self._scrollframe = scrollframe canvas.create_window(0, 0, window = scrollframe, anchor = N + W) scrollframe.rowconfigure(0, weight = 1) scrollframe.columnconfigure(0, weight = 1) self._mainframe = Frame(scrollframe) self._mainframe.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = NSEW) cf = Frame(scrollframe) self._control_frame = cf cf.grid(row = 1, column = 0, padx = 5, pady = 5, sticky = E) b = Button(cf, text = lang[lng.txtCopyImages], command = self._ehCopyImages) self._btnCopy = b b.grid(row = 0, column = 0, padx = 5, pady = 5) b = Button(cf, text = lang[lng.txtSave], command = self._ehSave, state = DISABLED) self._btnSave = b b.grid(row = 0, column = 1, padx = 5, pady = 5) b = Button(cf, text = lang[lng.txtClose], command = self._ehClose) b.grid(row = 0, column = 2, padx = 5, pady = 5) parentnotebook.after_idle(self._setCanvas)
def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command=self._listbox.yview) vbar.grid(row=0, column=1, sticky=N + S) self._listbox.configure( yscrollcommand=lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command=self._listbox.xview) hbar.grid(row=1, column=0, sticky=E + W) self._listbox.configure( xscrollcommand=lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight=1) listbox_frame.grid_rowconfigure(0, weight=1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height() - self.cget("borderwidth") - self.cget( "highlightthickness") if self._listbox_width: width = self._listbox_width else: width = self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item)
def __init__(self, parent, filename): Frame.__init__(self, parent) text = HelpText(self, filename) self['background'] = text['background'] scroll = Scrollbar(self, command=text.yview) text['yscrollcommand'] = scroll.set self.rowconfigure(0, weight=1) self.columnconfigure(1, weight=1) # text self.toc_menu(text).grid(column=0, row=0, sticky='nw') text.grid(column=1, row=0, sticky='nsew') scroll.grid(column=2, row=0, sticky='ns')
def generate_event_view(self): self.events_label = Label(self.frame, text="Eventos:") self.events_label.grid(column=0,row=2) self.events = Text(self.frame, width=100, highlightthickness=2) scroll=Scrollbar(self.frame) scroll.grid(column=6,row=3,sticky="ns") scroll.config(command=self.events.yview) self.events.configure(yscrollcommand=scroll.set) self.events.grid(column=0,row=3,rowspan=1,columnspan=5,sticky="nesw") self.events.tag_config("a", wrap=Tkinter.WORD) self.application.subscribe(self,"log_changed",self.log_changed) self.application.subscribe(self,"began_processing",self.began_normalizing)
class console: def __init__(self, master, font): self.Yscroll = Scrollbar(master) self.Yscroll.grid(column=1, sticky='nsew') self.height = 7 self.text = Text(master, padx=5, pady=5, height=self.height, bg="Black", fg="White", font=(font, 12), yscrollcommand=self.Yscroll.set) self.Yscroll.config(command=self.text.yview) self.text.bind("<Key>", lambda e: "break") self.text.grid(row=1, column=0, sticky="nsew") def __str__(self): """ str(s) -> string """ return self.text.get() def write(self, string): """ Adds string to the bottom of the console """ self.text.insert(END, string) self.text.see(END) return def read(self): """ Returns contents of the console widget """ return str(self) def hide(self): """ Removes console from interface """ self.text.grid_remove() self.Yscroll.grid_remove() return def show(self): self.text.grid() self.Yscroll.grid() return
def __init__(self, master, mech): self.mech = mech frame = Frame(master) frame.grid() rct_label = Label(frame, text = 'Select Reactants') rct_label.grid(column = 1, row = 1) and_or = Label(frame, text = 'AND/OR') and_or.grid(column = 3, row = 1) prod_label = Label(frame, text = 'Select Products') prod_label.grid(column = 4, row = 1) what_to_do = Label(frame, text = 'Execute') what_to_do.grid(column = 6, row = 1) reactants_scrollbar = Scrollbar(frame, orient = VERTICAL) self.reactants = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = reactants_scrollbar.set) self.reactants.grid(column = 1, row = 2) reactants_scrollbar.config(command = self.reactants.yview) reactants_scrollbar.grid(column = 2, row = 2, sticky = N + S) self.logical_and = IntVar() self.logical_and.set(1) c = Checkbutton(frame, text = "AND", variable = self.logical_and) c.grid(column = 3, row = 2) products_scrollbar = Scrollbar(frame, orient = VERTICAL) self.products = Listbox(frame, selectmode = EXTENDED, exportselection = 0) self.products.grid(column = 4, row = 2) products_scrollbar.config(command = self.products.yview) products_scrollbar.grid(column = 5, row = 2, sticky = N + S) self.method_list = Listbox(frame, selectmode = EXTENDED, exportselection = 0) self.method_list.grid(column = 6, row = 2) #self.methods = [k for k in dir(self.mech) if k[:1] != '_' and isinstance(getattr(self.mech, k), MethodType)] self.methods = ['plot_rxns', 'find_rxns', 'print_rxns', 'print_irrs', 'print_net_rxn', 'plot_proc'] method_labels= ['Plot Reactions', 'Show Rxn Ids', 'Print Rxns', 'Print IRRs', 'Print Net Rxn', 'Process Plot'] for method in method_labels: self.method_list.insert(END, method) species_keys = self.mech.species_dict.keys() species_keys.sort() self.species_objects = [self.mech.species_dict[spc] for spc in species_keys] for spc in species_keys: self.reactants.insert(END, spc) self.products.insert(END, spc) self.execute_button = Button(frame, text = "go", command = self.execute) self.execute_button.grid(column = 6, row = 4)
def __init__(self, parent): master = Frame(parent, bg = 'green') master.grid(sticky = W + N + E + S) master.rowconfigure(0, weight = 1) master.columnconfigure(0, weight = 1) canvas = Canvas(master) self._canvas = canvas canvas.grid(row = 0, column = 0, sticky = W + N + E + S) hScroll = Scrollbar(master, orient = HORIZONTAL, command = canvas.xview) hScroll.grid(row = 1, column = 0, sticky = W + E) vScroll = Scrollbar(master, orient = VERTICAL, command = canvas.yview) vScroll.grid(row = 0, column = 1, sticky = N + S) canvas.configure(xscrollcommand = hScroll.set, yscrollcommand = vScroll.set) Frame.__init__(self, canvas, bg = 'blue') canvas.create_window(0, 0, window = self, anchor = N + W)
class ScrolledCanvas: def __init__(self, master, **opts): if not opts.has_key('yscrollincrement'): opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) self.frame.rowconfigure(0, weight=1) self.frame.columnconfigure(0, weight=1) self.canvas = Canvas(self.frame, **opts) self.canvas.grid(row=0, column=0, sticky="nsew") self.vbar = Scrollbar(self.frame, name="vbar") self.vbar.grid(row=0, column=1, sticky="nse") self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") self.hbar.grid(row=1, column=0, sticky="ews") self.canvas['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.canvas.yview self.canvas['xscrollcommand'] = self.hbar.set self.hbar['command'] = self.canvas.xview self.canvas.bind("<Key-Prior>", self.page_up) self.canvas.bind("<Key-Next>", self.page_down) self.canvas.bind("<Key-Up>", self.unit_up) self.canvas.bind("<Key-Down>", self.unit_down) #if isinstance(master, Toplevel) or isinstance(master, Tk): self.canvas.bind("<Alt-Key-2>", self.zoom_height) self.canvas.focus_set() def page_up(self, event): self.canvas.yview_scroll(-1, "page") return "break" def page_down(self, event): self.canvas.yview_scroll(1, "page") return "break" def unit_up(self, event): self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): self.canvas.yview_scroll(1, "unit") return "break" def zoom_height(self, event): ZoomHeight.zoom_height(self.master) return "break"
def configure_scrolling(self): # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient='vertical') vscrollbar.grid(row=0,column=1,sticky='nsw') self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) self.canvas.grid(row=0,column=0,sticky='nsew') vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(self.canvas) self.interior.grid(row=0,column=0,sticky='nsew') self.interior_id = self.canvas.create_window(0, 0, window=interior, anchor='nw')
class console: def __init__(self, master, font): self.Yscroll = Scrollbar(master) self.Yscroll.grid(column=1, sticky='nsew') self.height = 7 self.text = Text( master, padx=5, pady=5, height=self.height, bg="Black", fg="White", font=(font, 12), yscrollcommand=self.Yscroll.set) self.Yscroll.config(command=self.text.yview) self.text.bind("<Key>", lambda e: "break") self.text.grid(row=1, column=0, sticky="nsew") def __str__(self): """ str(s) -> string """ return self.text.get() def write(self, string): """ Adds string to the bottom of the console """ self.text.insert( END, string ) self.text.see(END) return def read(self): """ Returns contents of the console widget """ return str(self) def hide(self): """ Removes console from interface """ self.text.grid_remove() self.Yscroll.grid_remove() return def show(self): self.text.grid() self.Yscroll.grid() return
class ApexListContainer(Frame): """This is a container for ApexList. Provides some additional buttons """ def __init__(self, parent, apex=None, **kw): if apex is None: apex = [] self._apex = apex Frame.__init__(self, parent, **kw) self._init_components() def _init_components(self): self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) upper_pane = Frame(self) upper_pane.columnconfigure(0, weight=1) upper_pane.rowconfigure(0, weight=1) self.apex_list = ApexList(upper_pane, self._apex) self.apex_list.grid(row=0, column=0, sticky='nesw') self._scrollbar_x = Scrollbar(upper_pane, command=self.apex_list.xview, orient='horizontal') self._scrollbar_x.grid(row=1, column=0, sticky='ews') self.apex_list['xscrollcommand'] = self._scrollbar_x.set self._scrollbar_y = Scrollbar(upper_pane, command=self.apex_list.yview) self._scrollbar_y.grid(row=0, column=1, sticky='nse') self.apex_list['yscrollcommand'] = self._scrollbar_y.set buttons_pane = Frame(self) self._expand_button = Button(buttons_pane, text="Expand all", command=self.apex_list.expand_all) self._expand_button.pack(side='left', expand=True, fill='x') self._reset_button = Button(buttons_pane, text="Reset", command=self.apex_list.reset) self._reset_button.pack() upper_pane.grid(sticky='nesw') buttons_pane.grid(row=1, sticky='nesw')
def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item)
def init(self): self.parent.title('FuzzyOctoDubstep') self.style = Style() self.style.theme_use('default') self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) conv_scrollbar = Scrollbar(self) conv_scrollbar.grid(row=1, column=2) conv = Listbox(self, width=80, height=30, yscrollcommand=conv_scrollbar.set) conv.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) conv.insert(END, 'Hello') conv_scrollbar.config(command=conv.yview) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def _init_components(self): self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) # add listbox self._listbox.grid(row=0, column=0, sticky='nesw') # add horizontal scrollbar if self._scroll_x: scrollbar_x = Scrollbar(self, command=self._listbox.xview, orient='horizontal') scrollbar_x.grid(row=1, column=0, sticky='ews') self._listbox['xscrollcommand'] = scrollbar_x.set if self._scroll_y: scrollbar_y = Scrollbar(self, command=self._listbox.yview) scrollbar_y.grid(row=0, column=1, sticky='nse') self._listbox['yscrollcommand'] = scrollbar_y.set
def __canvas(self, master): f = Frame(master) f.grid_columnconfigure(0, weight=1) f.grid_rowconfigure(0, weight=1) h = Scrollbar(f, orient=HORIZONTAL) v = Scrollbar(f, orient=VERTICAL) canvas = Canvas( f, background="white", xscrollcommand=h.set, yscrollcommand=v.set, ) h['command'] = canvas.xview v['command'] = canvas.yview canvas.bind("<4>", lambda e: self.scale_view(e, 1.0 * 1.1)) canvas.bind("<5>", lambda e: self.scale_view(e, 1.0 / 1.1)) # in windows, mouse wheel events always go to the root window o_O self.master.bind("<MouseWheel>", lambda e: self.scale_view( e, ((1.0 * 1.1) if e.delta > 0 else (1.0 / 1.1)) )) # Drag based movement # def _sm(e): # self.st = self.render_start.get() # self.sx = e.x # self.sy = e.y # def _cm(e): # self.render_start.set(self.st + float(self.sx - e.x)/self.scale.get()) # self.render() # self.canvas.bind("<1>", _sm) # self.canvas.bind("<B1-Motion>", _cm) canvas.grid(column=0, row=0, sticky=(N, W, E, S)) v.grid(column=1, row=0, sticky=(N, S)) h.grid(column=0, row=1, sticky=(W, E)) self.canvas = canvas return f
def nvnReport(self): #interface for "Display probeset specific report" top = Toplevel() top.title("Co-expression analysis") self.genelist = [] for string in self.queries: self.genelist.append(string.split()) self.listbox = Listbox(top, width=40, height=30, exportselection=0) for gene in self.genelist: self.listbox.insert(END, gene[0] + ' ' + gene[1]) DescriptionLabel = LabelFrame(top, text="Info") Description = Label( DescriptionLabel, text= "Select gene of interest from the list to the left.\nThis tool will generate result.html file containing a page similar to\ngene specific pages in PlaNet." ) DescriptionLabel.grid(row=0, column=2) ParametersLabel = LabelFrame(top, text="Parameters") Steps = Label(ParametersLabel, text="Number of steps") ParametersLabel.grid(row=1, column=2) Hrr = Label(ParametersLabel, text="HRR cut-off.") self.paraSteps = Entry(ParametersLabel) self.paraSteps.grid(row=1) self.paraSteps.insert(END, 2) self.paraHrr = Entry(ParametersLabel) self.paraHrr.grid(row=3) self.paraHrr.insert(END, 30) Description.grid() Steps.grid(row=0) Hrr.grid(row=2) scrollbar = Scrollbar(top) scrollbar.grid(row=0, column=1, rowspan=5, sticky=S + N) self.listbox.grid(row=0, column=0, rowspan=5) scrollbar.config(command=self.listbox.yview) button = Button(top, text="Calculate!", fg="red", font=("Courier", 22), command=self.nvnReportPipe) button.grid(row=6, column=0)
def ancestranNetPipe(self): #Interface top = Toplevel() top.title("NetworkComparer") a = open("NetComp.html", "r").readlines() self.queriesAC = [] quera = 0 for i in range(len(a)): if "START OF QUERIES" in a[i]: self.queryOrder = a[i + 1].rstrip().split() if "START OF VS. QUERY" in a[i]: quera = 1 if quera == 1: self.queriesAC.append(a[i].rstrip().split("\t")) self.queriesAC = self.queriesAC[1:len(self.queriesAC) - 1] DescriptionLabel = LabelFrame( top, text="Select the gene of interest and specify parameters.") Description = Label( DescriptionLabel, text= "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer." ) DescriptionLabel.grid(row=0, column=0) Description.grid(row=0) self.listbox = Listbox(DescriptionLabel, width=40, height=30, exportselection=0, selectmode=MULTIPLE) for gene in self.queriesAC: self.listbox.insert( END, gene[0] + ' ' + gene[1] + ' ' + gene[2] + ' ' + gene[3] + ' ' + gene[4]) self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W) scrollbarG = Scrollbar(DescriptionLabel) scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N) scrollbarG.config(command=self.listbox.yview) button = Button(top, text="Calculate!", fg="red", font=("Courier", 22), command=self.ancestralNet) button.grid(row=1, column=0, columnspan=5, sticky=E + W)
def __init__(self, parent, width=100, height=100, bg="white", scrollregion=(0, 0, 300, 300)): Frame.__init__(self, parent) self.canvas = Canvas(self, width=width - 20, height=height - 20, bg=bg, scrollregion=scrollregion) self.canvas.grid(row=0, column=0) scv = Scrollbar(self, orient="vertical", command=self.canvas.yview) sch = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.canvas.configure(xscrollcommand=sch.set, yscrollcommand=scv.set) scv.grid(row=0, column=1, sticky="ns") sch.grid(row=1, column=0, sticky="ew") self.bind("<Configure>", self.resize) self.config = False self.bind("<Configure>", self.resize)
class ScrolledCanvas: def __init__(self, master, **opts): if 'yscrollincrement' not in opts: opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) self.frame.rowconfigure(0, weight=1) self.frame.columnconfigure(0, weight=1) self.canvas = Canvas(self.frame, **opts) self.canvas.grid(row=0, column=0, sticky="nsew") self.vbar = Scrollbar(self.frame, name="vbar") self.vbar.grid(row=0, column=1, sticky="nse") self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") self.hbar.grid(row=1, column=0, sticky="ews") self.canvas['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.canvas.yview self.canvas['xscrollcommand'] = self.hbar.set self.hbar['command'] = self.canvas.xview self.canvas.bind("<Key-Prior>", self.page_up) self.canvas.bind("<Key-Next>", self.page_down) self.canvas.bind("<Key-Up>", self.unit_up) self.canvas.bind("<Key-Down>", self.unit_down) #if isinstance(master, Toplevel) or isinstance(master, Tk): self.canvas.bind("<Alt-Key-2>", self.zoom_height) self.canvas.focus_set() def page_up(self, event): self.canvas.yview_scroll(-1, "page") return "break" def page_down(self, event): self.canvas.yview_scroll(1, "page") return "break" def unit_up(self, event): self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): self.canvas.yview_scroll(1, "unit") return "break" def zoom_height(self, event): ZoomHeight.zoom_height(self.master) return "break"
def configure_scrolling(self): # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient='vertical') vscrollbar.grid(row=0, column=1, sticky='nsw') self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) self.canvas.grid(row=0, column=0, sticky='nsew') vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(self.canvas) self.interior.grid(row=0, column=0, sticky='nsew') self.interior_id = self.canvas.create_window(0, 0, window=interior, anchor='nw')
def construct(self): """ Construct the window and the frame used to display the XML :return: """ top = Toplevel() top.withdraw() top.protocol("WM_DELETE_WINDOW", self.view_xml_pane) top.columnconfigure(0, weight=1) top.rowconfigure(0, weight=1) top.title("XML Preview") self._pane = top xml_area = Text(top, borderwidth=2, relief="sunken") xml_area.config(font=("consolas", 12), undo=True, wrap='word', state=DISABLED) xml_area.grid(row=0, column=0, sticky="nsew", padx=2, pady=2) scrollbar = Scrollbar(top, command=xml_area.yview) scrollbar.grid(row=0, column=1, sticky='nsew') xml_area['yscrollcommand'] = scrollbar.set self._text_area = xml_area
def createWidgets(self): "Create initial widget set." # Objects title = Label(self, text="Bandwidth (Gb/s)", bg=self.bg) width = self.gwidth height = self.gheight scale = self.createScale() graph = Canvas(self, width=width, height=height, background=self.bg) xbar = Scrollbar(self, orient="horizontal", command=graph.xview) ybar = Scrollbar(self, orient="vertical", command=self.yview) graph.configure(xscrollcommand=xbar.set, yscrollcommand=ybar.set, scrollregion=(0, 0, width, height)) scale.configure(yscrollcommand=ybar.set) # Layout title.grid(row=0, columnspan=3, sticky="new") scale.grid(row=1, column=0, sticky="nsew") graph.grid(row=1, column=1, sticky="nsew") ybar.grid(row=1, column=2, sticky="ns") xbar.grid(row=2, column=0, columnspan=2, sticky="ew") self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) return title, scale, graph
def __init__(self, parent=None, bg="white", bd=2, scrollregion=(0, 0, 300, 300), relief="sunken"): Frame.__init__(self, parent, bd=bd, relief=relief) self.parent = parent self.canvas = Canvas(self, bg=bg, bd=1, scrollregion=scrollregion) scv = Scrollbar(self, orient="vertical", command=self.canvas.yview, bd=1) sch = Scrollbar(self, orient="horizontal", command=self.canvas.xview, bd=1) self.canvas.configure(xscrollcommand=sch.set, yscrollcommand=scv.set) self.canvas.grid(row=0, column=0) scv.grid(row=0, column=1, sticky="ns") sch.grid(row=1, column=0, sticky="ew") self.config = False self.bind("<Configure>", self.resize)
def setKernelList(self): self.kernelList = [] for i in xrange(len(self.RepLine.cobs[self.activeCob])): self.kernelList.append("Kernel: " + str(i + 1)) if "kernelListbox" in self.widgetDict.keys(): kernelListbox = self.widgetDict["kernelListbox"] kernelListbox.delete(0, "end") self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) else: kernelListbox = Listbox(self) self.widgetDict["kernelListbox"] = kernelListbox scrollbar = Scrollbar(kernelListbox, orient="vertical") kernelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=kernelListbox.yview) self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) kernelListbox.grid(row=3, column=1, rowspan=3, sticky="nsew") kernelListbox.columnconfigure(0, weight=1) kernelListbox.bind("<<ListboxSelect>>", self.updateActiveKernel) scrollbar.grid(column=1, sticky="e") for kernel in self.kernelList: kernelListbox.insert(self.kernelList.index(kernel), kernel)
def init(self): self.parent.title('FuzzyOctoDubstep') self.style = Style() self.style.theme_use('default') self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Windows") lbl.grid(sticky=W, pady=4, padx=5) conv_scrollbar = Scrollbar(self) conv_scrollbar.grid(row=1, column=2) conv = Listbox(self, width=80, height=30, yscrollcommand=conv_scrollbar.set) conv.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N) conv.insert(END, 'Hello') conv_scrollbar.config(command=conv.yview) abtn = Button(self, text="Activate") abtn.grid(row=1, column=3) cbtn = Button(self, text="Close") cbtn.grid(row=2, column=3, pady=4) hbtn = Button(self, text="Help") hbtn.grid(row=5, column=0, padx=5) obtn = Button(self, text="OK") obtn.grid(row=5, column=3)
def setCobList(self): self.cobList = [] for cob in xrange(len(self.RepLine.cobs.keys())): self.cobList.append( str(cob + 1) + "_" + self.RepLine.accessionName) if "cobListbox" in self.widgetDict.keys(): cobListbox = self.widgetDict["cobListbox"] cobListbox.delete(0, "end") self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) else: cobListbox = Listbox(self) self.widgetDict["cobListbox"] = cobListbox scrollbar = Scrollbar(cobListbox, orient="vertical") cobListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=cobListbox.yview) self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) cobListbox.grid(row=3, column=0, rowspan=3, sticky="nsew") cobListbox.columnconfigure(0, weight=1) cobListbox.bind("<<ListboxSelect>>", self.updateActiveCob) scrollbar.grid(column=0, sticky="e") for cob in self.cobList: cobListbox.insert(self.cobList.index(cob), cob)
relief="solid", background="#d6feca", text="label 7 to see how does it work !").pack(padx=1, pady=2, anchor="center", expand="yes") Label(scrollframe(), relief="solid", background="#d6feca", text="label 8 to see how does it work !").pack(padx=1, pady=2, fill="both", expand="yes") scrollx = Scrollbar(root, orient="horizontal", command=scrollframe.xview) scrollx.grid(row=1, column=0, sticky="nwse") scrolly = Scrollbar(root, orient="vertical", command=scrollframe.yview) scrolly.grid(row=0, column=1, sticky="nwse") scrollframe["xscrollcommand"] = scrollx.set scrollframe["yscrollcommand"] = scrolly.set scrollframe.grid(row=0, column=0, sticky="nwse") checkvar = BooleanVar(root, value=scrollframe["stretch"]) def set_stretch(): scrollframe["stretch"] = True if checkvar.get() else False scrollframe.update_scrollregion() stretch = Checkbutton(root, anchor="w",
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.padx = 3 self.pady = 3 self.grid() self.results = [] self.playlists = [] self.vids = [] self.__createWidgets() def __createWidgets(self): self.__searchFields() self.__resultArea() self.__buttons() self.__markdownArea() self.bind('<Return>', self.search_button) def __buttons(self): self.resultSelect = Button(text='OK', state=DISABLED) self.resultSelect.grid(row=5, column=4, sticky=E, padx=self.padx, pady=self.pady) self.status = Label(text="", bd=1, relief=SUNKEN, anchor=W) self.status.grid(row=9, column=0, columnspan=10, sticky=N + E + S + W) self.__vidButtons() self.__rmVidButtons() self.resultSelect.grid_forget() def __searchFields(self): Label(text="User", anchor=E).grid(row=0, column=0, padx=self.padx, pady=self.pady, sticky=W) self.user_entry = Entry() self.user_entry.grid(row=0, column=1, padx=self.padx, pady=self.pady, sticky=W) Label(text="Search terms").grid(row=0, column=3, padx=self.padx, pady=self.pady, sticky=W) self.search_terms = Entry() self.search_terms.grid(row=0, column=4, padx=self.padx, pady=self.pady, sticky=W) Label(text="playlist id").grid(row=1, column=3, padx=self.padx, pady=self.pady, sticky=W) self.playlist_id = Entry() self.playlist_id.grid(row=1, column=4, padx=self.padx, pady=self.pady, sticky=W) self.search_button = Button(text="Search", command=self.__search) self.search_button.grid(row=2, column=4, padx=self.padx, pady=self.pady, sticky=E) def __resultArea(self): self.result_label = Label(text="Results") self.result_label.grid(row=2, column=0, padx=self.padx, pady=self.pady, sticky=W) self.resultshowbut = Button(text="View", command=self.__showResults) self.resultshowbut.grid(row=2, column=1, sticky=W) self.yScroll = Scrollbar(orient=VERTICAL) self.xScroll = Scrollbar(orient=HORIZONTAL) self.listbox = Listbox(xscrollcommand=self.xScroll.set, yscrollcommand=self.yScroll.set, selectmode=SINGLE) self.xScroll.config(command=self.listbox.xview) self.yScroll.config(command=self.listbox.yview) def __showResults(self): self.resultshowbut.config(text="Hide", command=self.__hideResults) self.yScroll.grid(row=3, column=5, sticky=N + S) self.xScroll.grid(row=4, column=0, sticky=E + W, columnspan=5) self.listbox.grid(row=3, column=0, sticky=N + S + E + W, columnspan=5) self.markdownarea.config(height=10) def __hideResults(self): self.resultshowbut.config(text="View", command=self.__showResults) self.yScroll.grid_forget() self.xScroll.grid_forget() self.listbox.grid_forget() self.markdownarea.config(height=30) def __markdownArea(self): self.markdownlabel = Label(text="Markdown") self.mdyScroll = Scrollbar(orient=VERTICAL) self.mdxScroll = Scrollbar(orient=HORIZONTAL) self.markdownarea = Text(wrap=WORD, height=10, yscrollcommand=self.mdyScroll.set, xscrollcommand=self.mdxScroll.set) self.copymarkdown = Button(text="Copy To Clipboard", command=self.__copyMarkdown) self.mdxScroll.config(command=self.markdownarea.xview) self.mdyScroll.config(command=self.markdownarea.yview) def __vidButtons(self): self.modtitle = Button(text='Modify titles', command=self.__modTitles) #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2, # padx=self.padx, pady=self.pady) self.getcaps = Button(text="Get captions", command=self.__getCaptions) self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E, padx=self.padx, pady=self.pady) def __rmVidButtons(self): self.modtitle.grid_remove() self.getcaps.grid_remove() self.bind('<Return>', self.search_button) def __search(self): user = self.user_entry.get() playlist = self.playlist_id.get() searchterms = self.search_terms.get() self.__showResults() self.resultSelect.config(state=DISABLED) self.__rmVidButtons() self.__rmMarkdown() if not self.__validparams(user, searchterms, playlist): return False if len(playlist) > 0: self.__searchPlaylist(playlist) return self.__searchUser(user, searchterms) def __showMarkdown(self): self.markdownlabel.grid(row=5, column=0, padx=self.padx, pady=self.pady, sticky=W) self.markdownarea.grid(row=6, column=0, columnspan=5, padx=self.padx, pady=self.pady, sticky=N + S + E + W) self.mdyScroll.grid(row=6, column=5, sticky=N + S) self.mdxScroll.grid(row=7, column=0, sticky=E + W, columnspan=5) self.copymarkdown.grid(row=8, column=2, columnspan=3, sticky=E, padx=self.padx, pady=self.pady) def __rmMarkdown(self): self.markdownarea.grid_forget() self.markdownlabel.grid_forget() self.copymarkdown.grid_forget() self.mdyScroll.grid_forget() self.mdxScroll.grid_forget() def __searchPlaylist(self, playlistid): self.__getvids(playlistid) def __searchUser(self, user, searchterms): self.listbox.delete(0, END) self.__status("Searching for%splaylists by user \"%s\"" % ( " \"%s\" " % searchterms if len(searchterms) else " ", user)) self.playlists = [] try: self.playlists = lib.yt.search.PlaylistSearch(user=user, search=searchterms).query() except HTTPError: self.__status("User %s does not exist at youtube" % user) return if self.playlists is None or len(self.playlists) == 0: self.__status("Search returned no results") return self.__populateResults([v['title'] for v in self.playlists]) self.resultSelect.config(command=self.__getVidsFromSelected, state=NORMAL) self.__status("") self.resultSelect.grid(row=5, column=4, sticky=E, padx=self.padx, pady=self.pady) def __populateResults(self, values): self.listbox.delete(0, END) for i, val in enumerate(values): self.listbox.insert(i, val) self.listbox.activate(0) self.listbox.selection_set(0) def __getVidsFromSelected(self): selected = int(self.listbox.curselection()[0]) self.__getvids(self.playlists[selected]['id']) def __getvids(self, playlistid): self.playlist_id.delete(0, END) self.playlist_id.insert(0, playlistid) self.resultSelect.grid_forget() title = playlistid if len(self.playlists) > 0: for playlist in self.playlists: if playlist['id'] == playlistid: title = playlist['title'] break self.__status("Getting videos for %s" % title) self.listbox.delete(0, END) try: self.vids = lib.yt.search.PlaylistVideoSearch( id=playlistid).query() self.__populateResults([v['title'] for v in self.vids]) self.__status("%d Videos found" % len(self.vids)) self.__vidButtons() self.bind('<Return>', self.getcaps) except HTTPError: self.__status("No videos found! is %s a valid playlist?" % playlistid) def __status(self, msg): if len(msg) > 75: msg = msg[:70] + '...' self.status.config(text=msg) self.status.update_idletasks() def __trackSelect(self, vid, tracks, preftrack=None): pref = self.__prefAvailable(preftrack, tracks) if pref is None: sel = lib.trackSelect.TrackSelect(self, vid=vid, tracks=tracks) if sel.result is None: self.__status("skipped") tracks = None else: tracks = [sel.result[0]] if sel.preflang is not None: preftrack['lang'] = sel.preflang if sel.prefname is not None: preftrack['name'] = sel.prefname else: tracks = pref return tracks, preftrack def __getCaptions(self): preftrack = {'name': None, 'lang': None} self.listbox.delete(0, END) self.markdownarea.delete(1.0, END) self.__showMarkdown() for i, vid in enumerate(self.vids): nocapmsg = '[%02d] --NO CAPTIONS-- %s' % (i + 1, vid['title']) tracks = lib.yt.search.CaptionSearch(id=vid['id']).query() self.vids[i]['text'] = '' if len(tracks) == 0: self.__status('No captions available for %s' % self.vids[i]['title']) self.listbox.insert(END, nocapmsg) elif len(tracks) > 1: sel = self.__trackSelect(vid, tracks, preftrack) if sel[0] is None: msg = '[%02d] --SKIPPED-- %s' % (i + 1, vid['title']) self.listbox.insert(END, msg) self.listbox.see(END) continue tracks = sel[0] if len(tracks) == 1: self.__trackCaps(i, tracks, nocapmsg) self.__status('') self.__hideResults() def __trackCaps(self, vidIndex, tracks, nocapmsg): i = vidIndex vid = self.vids[i] msg = '%02d of %02d Getting captions for %s' % ( i + 1, len(self.vids), self.vids[i]['title']) self.__status(msg) self.listbox.insert(END, msg) self.vids[i]['text'] = lib.markdown.heading(vid['title']) captions = lib.yt.search.GetCaptions(id=vid['id'], lang=tracks[0]['lang'], name=tracks[0]['name']) captions.query() captiontext = captions.textOnly() sleep(0.2) msg = nocapmsg if captiontext is not None and len(captiontext) > 0: self.vids[i]['text'] += (lib.markdown.to_utf8(captiontext) + '\n\n') msg = '[%02d] --DONE-- %s' % (i + 1, vid['title']) self.listbox.delete(END, END) self.listbox.insert(END, msg) self.listbox.see(END) self.markdownarea.insert(END, self.vids[i]['text']) self.markdownarea.see(END) def __prefAvailable(self, preftrack, tracks): if preftrack['lang'] is None: return None pref = None for track in tracks: if (track['lang'] == preftrack['lang'] and track['name'] == preftrack['name']): return [track] if track['lang'] == preftrack['lang'] and pref is None: pref = [track] return pref def __modTitles(self): pass def __validparams(self, user, searchterms, playlist): if len(user) == 0 and len(playlist) == 0: msg = "Either a valid youtube user or playlist id must be given." tkMessageBox.showwarning("missing information", msg) return False if len(user) > 0 and not self.__validstring(user): msg = "The user given contains invalid characters" tkMessageBox.showwarning('Bad user', msg) return False if len(playlist) > 0 and not self.__validstring(playlist): msg = "The playlist given contains invalid characters" tkMessageBox.showwarning('Bad playlist', msg) return False if len(searchterms) > 0 and not self.__validstring(searchterms, True): msg = "The search terms given contain invalid characters" tkMessageBox.showwarning('Bad search', msg) return False return True def __validstring(self, s, spacechar=False): validchars = string.letters + string.digits + string.punctuation if spacechar: validchars += ' ' for c in s: if c not in validchars: return False return True def __copyMarkdown(self): self.markdownarea.clipboard_clear() self.markdownarea.clipboard_append(self.markdownarea.get(1.0, END))
class GEditor: def __init__(self, parent, gcode, fname): self.textChanged = False self.app = parent self.fname = fname top = self.top = Toplevel(parent) if fname != None: self.top.title(fname) else: self.top.title("Live GCode") self.editBox = Text(top) self.editBox.grid(row=1, column=1, sticky=N+E+W+S) self.sb = Scrollbar(top) self.sb.config(command=self.editBox.yview) self.sb.grid(column=2, row=1, sticky=N+S+E) self.editBox.tag_configure("mymatch",foreground="#ff0000") self.matchStart = None self.matchEnd = None self.editBox.config(yscrollcommand=self.sb.set) self.editBox.delete("1.0", END) for l in gcode: self.editBox.insert(END, l + '\n') self.editBox.mark_set("insert", "1.0") self.editBox.edit_modified(False) self.editBox.bind('<<Modified>>', self.changed) bf = Frame(top) bf.grid(row=2, column=1, columnspan=2) self.bCancel = Button(bf, text='Exit', command=self.doCancel, width=6) self.bCancel.pack(side=LEFT, padx=2, pady=2) self.bSave = Button(bf, text='Save', command=self.doSave, width = 6, state=DISABLED) self.bSave.pack(side=LEFT, padx=2, pady=2) self.bSearch = Button(bf, text="Search", command=self.doSearch, width=6) self.bSearch.pack(side=LEFT, padx=2, pady=2) self.eSearch = Entry(bf, width=30) self.eSearch.pack(side=LEFT, padx=2) self.bReplace = Button(bf, text="Replace", command=self.doReplace, width=6) self.bReplace.pack(side=LEFT, padx=2, pady=2) self.eReplace = Entry(bf, width=30) self.eReplace.pack(side=LEFT, padx=2) self.top.grab_set() self.app.wait_window(self.top) def doCancel(self): if not self.textChanged: self.top.destroy() elif tkMessageBox.askyesno("Cancel?", "Are you sure you want to lose your changes?", parent=self.top): self.top.destroy() def doSave(self): rc = self.app.gEditSave(self.editBox.get("1.0", END).rstrip().split("\n"), self.fname, self.top) if self.fname == None: self.top.destroy() else: if rc: self.editBox.edit_modified(False) self.textChanged = False self.bCancel.config(text="Exit") self.bSave.config(state=DISABLED) def changed(self, evt): if not self.textChanged: self.bSave.config(state=NORMAL) self.bCancel.config(text="Cancel") self.textChanged = True def doSearch(self): sval = self.eSearch.get() if len(sval) == 0: return try: start = self.editBox.index(INSERT + "+1c") except: start = "1.0" pos = self.editBox.search(sval, start, stopindex=END) if not pos: pos = self.editBox.search(sval, "1.0", stopindex=start) if not pos: return e = self.editBox.index(pos + "+%dc" % len(sval)) self.editBox.see(pos) self.editBox.mark_set("insert", pos) if self.matchStart != None: self.editBox.tag_remove("mymatch", self.matchStart, self.matchEnd) self.editBox.tag_add("mymatch", pos, e) self.matchStart = pos self.matchEnd = e self.editBox.focus_force() def doReplace(self): rval = self.eReplace.get() if self.matchStart == None: return self.editBox.delete(self.matchStart, self.matchEnd) self.editBox.insert(self.matchStart, rval) self.editBox.focus_force()
class TrackSelect(tkSimpleDialog.Dialog): def __init__(self, master, **kwargs): self.vid = {'title': "this video"} self.tracks = [] for k in kwargs: k = k.lower() if k == "master": self.master = kwargs[k] continue if k == "vid": self.vid = kwargs[k] continue if k == "tracks": self.tracks = kwargs[k] continue self.padx = 3 self.pady = 3 self.prefl = IntVar() self.preft = IntVar() self.preflang = None self.prefname = None tkSimpleDialog.Dialog.__init__(self, master, "Select caption track") def body(self, master): Label(master, text="%s contains multiple caption tracks" % self.vid['title']).grid(row=0, padx=self.padx, pady=self.pady, sticky=W, columnspan=5) self.__langlist(master) self.chosenlangbut = Button(master, text="->", command=self.__chooselang) self.chosenlangbut.grid(row=1, column=2, padx=self.padx, pady=self.pady) self.__tracklist(master) self.__fillLangs() return self.langsel # initial focus def __tracklist(self, master): self.trackYscroll = Scrollbar(master, orient=HORIZONTAL) self.trackXscroll = Scrollbar(master, orient=VERTICAL) self.tracksel = Listbox(master, xscrollcommand=self.trackXscroll.set, yscrollcommand=self.trackYscroll.set, selectmode=SINGLE) self.tracksel.grid(row=1, column=3, sticky=N + S + E + W) self.trackXscroll.grid(row=1, column=4, sticky=W + N + S) self.trackYscroll.grid(row=2, column=3, stick=N + E + W) self.trackXscroll.config(command=self.tracksel.xview) self.trackYscroll.config(command=self.tracksel.yview) self.preftracksel = Checkbutton(master, variable=self.preft, text="Set default track name") self.preftracksel.grid(row=3, column=3, sticky=W) def __langlist(self, master): self.langYscroll = Scrollbar(master, orient=HORIZONTAL) self.langXscroll = Scrollbar(master, orient=VERTICAL) self.langsel = Listbox(master, xscrollcommand=self.langXscroll.set, yscrollcommand=self.langYscroll.set, selectmode=SINGLE, width=6) self.langsel.grid(row=1, column=0, sticky=N + S + E + W) self.langXscroll.grid(row=1, column=1, sticky=W + N + S) self.langYscroll.grid(row=2, column=0, stick=N + E + W) self.langXscroll.config(command=self.langsel.xview) self.langYscroll.config(command=self.langsel.yview) self.preflangsel = Checkbutton(master, variable=self.prefl, text="Set default language") self.preflangsel.grid(row=3, column=0, sticky=W) def __fillLangs(self): self.langsadded = [] for track in self.tracks: lang = track['lang'] if lang not in self.langsadded: self.langsel.insert(END, lang) self.langsadded.append(lang) def __chooselang(self): lang = self.langsadded[int(self.langsel.curselection()[0])] self.langselected = lang self.trackoptions = [] self.tracksel.delete(0, END) for track in self.tracks: if track['lang'] == lang: name = 'Default' if len(track['name']) == 0 else track['name'] self.tracksel.insert(END, name) self.trackoptions.append(track) self.tracksel.activate(0) self.tracksel.selection_set(0) def apply(self): selected = int(self.tracksel.curselection()[0]) self.result = [self.trackoptions[selected]] if int(self.prefl.get()) == 1: self.preflang = self.langselected if int(self.preft.get()) == 1: self.prefname = self.trackoptions[ int(self.tracksel.curselection()[0])]['name'] def buttonbox(self): box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Skip", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack()
def initUI(self): self.parent.title("Script Runner/Caller") # self.style = Style() # self.style.theme_use("default") self.pack(fill=BOTH, expand=1) #create a grid 5x4 in to which we will place elements. self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=0) self.columnconfigure(3, weight=0) self.columnconfigure(4, weight=0) self.columnconfigure(5, weight=0) self.rowconfigure(1, weight=1) self.rowconfigure(2, weight=0) self.rowconfigure(3, weight=0) #create the main text are with scrollbars xscrollbar = Scrollbar(self, orient=HORIZONTAL) xscrollbar.grid(row=2, column=1, columnspan=4, sticky=E + W) yscrollbar = Scrollbar(self, orient=VERTICAL) yscrollbar.grid(row=1, column=5, sticky=N + S) self.textarea = Text(self, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.textarea.grid(row=1, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) xscrollbar.config(command=self.textarea.xview) yscrollbar.config(command=self.textarea.yview) #create the buttons/checkboxes to go along the bottom self.clearButton = Button(self, text="Clear") self.clearButton.grid(row=3, column=1, padx=5, pady=5, sticky=W) self.clearButton.bind("<ButtonRelease-1>", self.clearText) self.runbutton = Button(self, text="Run/Call") self.runbutton.grid(row=3, column=3, padx=5, pady=5) self.runbutton.bind("<ButtonRelease-1>", self.runScript) self.stopbutton = Button(self, text="Stop") self.stopbutton.grid(row=3, column=4, padx=5, pady=5) self.stopbutton.bind("<ButtonRelease-1>", self.stopScript) #tags are used to colorise the text added to the text widget. # see self.addTtext and self.tagsForLine self.textarea.tag_config("errorstring", foreground="#CC0000") self.textarea.tag_config("infostring", foreground="#008800") self.addText("Path A: " + os.getcwd() + "\n", ("infostring", )) self.addText("(chdir)" + "\n", ("infostring", )) os.chdir(dirname(os.path.realpath(__file__))) self.addText("Path B: " + os.getcwd() + "\n\n", ("infostring", )) self.addText("Script is: " + " ".join(scriptcall) + "\n\n", ("infostring", ))
class ShowToolkitGui: # Initial data used. directory_path = None file_path = None DIRECTORY = 'directory' FILE = 'file' last_selected = None # Initialize module classes. file_rename = FileRename() char_replace = CharReplace() def __init__(self, master): self.master = master self.master.title('TV Show Tookit') # Create app layout. self.create_custom_layout() self.create_top_controls() self.create_status_controls() def create_custom_layout(self): """ Parent layout, divide the app into blocks for easier handling. """ # Main container for the whole app. self.main_container = Frame(self.master) self.main_container.pack(side='top', fill='both', expand=True) # Container for the top part of the app. self.top_frame = Frame(self.main_container) self.top_frame.pack(side='top', fill='x', expand=False) # Container for the bottom part of the app. self.bottom_frame = Frame(self.main_container) self.bottom_frame.pack(side='bottom', fill='both', expand=True) # Top container of the top container. self.top_top_frame = Frame(self.top_frame) self.top_top_frame.pack(side='top', fill='x', expand=False, padx=5, pady=5) # Bottom container of the top container. self.top_bottom_frame = Frame(self.top_frame) self.top_bottom_frame.pack(side='bottom', fill='x', expand=False) # Additional layers, divide top frame of top frame into left and right. self.top_top_left_frame = Frame(self.top_top_frame, relief='groove', borderwidth=2) self.top_top_left_frame.pack(side='left', fill='x', expand=False, padx=5, pady=5) self.top_top_right_frame = Frame(self.top_top_frame, relief='groove', borderwidth=2) self.top_top_right_frame.pack(side='right', fill='x', expand=False, padx=5, pady=5) def create_top_controls(self): """ Top layout, controls for the app. """ # Button for selecting directory. self.select_directory_button = Button(self.top_top_left_frame, text='Select Directory', command=self.select_directory) self.select_directory_button.grid(row=0, column=0, sticky=W + E, padx=7, pady=2) # Button for selecting file. self.select_file_button = Button(self.top_top_left_frame, text='Select File', command=self.select_file) self.select_file_button.grid(row=1, column=0, sticky=W + E, padx=7, pady=2) # Button to run the Rename operation. self.rename_button = Button(self.top_top_right_frame, text='Rename to S**E**', command=self.process_rename) self.rename_button.grid(row=0, column=0, sticky=W + E, padx=7, pady=2) # Button to run the Character Replace operation. self.char_button = Button(self.top_top_right_frame, text='Character Replace', command=self.process_character_replace) self.char_button.grid(row=1, column=0, sticky=W + E, padx=7, pady=2) def create_status_controls(self): """ Bottom layout, text status controls for letting the user know what the current state is. """ # Status text for currently selected directory or file. self.status_text = StringVar() self.status_label = Label(self.top_bottom_frame, textvariable=self.status_text) self.status_text.set( 'Use controls above to select a source to be modified') self.status_label.grid(row=0, column=0) # Progress text controls, outputs full logs from libs. self.progress_text = Text(self.bottom_frame, height=8, width=60) # Add visible scrollbar. self.scrollbar = Scrollbar(self.bottom_frame, command=self.progress_text.yview) self.progress_text.configure(yscrollcommand=self.scrollbar.set) # Define custom tags for text format. self.progress_text.tag_config('bold', background='black', foreground='green', font=('Arial', 12, 'bold')) self.progress_text.tag_config('big', background='black', foreground='green', font=('Arial', 20, 'bold')) self.progress_text.tag_config('default', foreground='red', font=('Courier', 11)) # Set initial empty text and position. self.update_progress_text('') self.progress_text.grid(row=0, column=0, sticky='nsew') # Add North and South to the scrollbar so it streches in vertical direction. self.scrollbar.grid(column=1, row=0, sticky=N + S + W) def select_directory(self): """ Get the selected directory path. """ # Open directory selector. self.directory_path = askdirectory() # If user selected a directory, mark it. if self.directory_path: self.last_selected = self.DIRECTORY self.status_text.set(self.directory_path) def select_file(self): """ Get the selected file path. """ # Open file selector, only some file types are supported. self.file_path = askopenfilename( filetypes=(('SRT Files', '*.srt'), ('SUB Files', '*.sub'), ('TXT Files', '*.txt'), ('AVI Files', '*.avi'), ('MP4 Files', '*.mp4'), ('MKV Files', '*.mkv'))) # If user selected a file, mark it. if self.file_path: self.last_selected = self.FILE self.status_text.set(self.file_path) def process_rename(self): """ Call the rename operation on directory or file selected. """ if not self.last_selected: return if self.last_selected == self.DIRECTORY: progress_message = self.file_rename.process_directory( self.directory_path) elif self.last_selected == self.FILE: progress_message = self.file_rename.rename_file(self.file_path) self.update_progress_text(progress_message) def process_character_replace(self): """ Call the char replace operation on directory or file selected. """ if not self.last_selected: return if self.last_selected == self.DIRECTORY: progress_message = self.char_replace.process_directory( self.directory_path) elif self.last_selected == self.FILE: progress_message = self.char_replace.process_file(self.file_path) self.update_progress_text(progress_message) def update_progress_text(self, new_text): """ Update the progress text from the rename or character replace operations. """ # If list is sent convert it to string. if type(new_text) is list: new_text = '\n'.join(new_text) # Enable the changes on text, clear it, send new content, and then disable editing. self.progress_text.config(state='normal') self.progress_text.delete(1.0, END) self.progress_text.insert(END, new_text, ('default')) self.progress_text.config(state='disabled')
class PypeTkPad(object): def __init__(self, master, queue, pypeOutput): self.queue = queue self.pypeOutput = pypeOutput self.master = master self.master.title('PypePad') self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0)) self.master.minsize(300, 100) self.output_file_name = None self.BuildMainFrame() self.UpdateOutput() def NewCommand(self): self.ClearAllCommand() def OpenCommand(self): import tkFileDialog from Tkinter import END openfile = tkFileDialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END,line) def SaveCommand(self): import tkFileDialog from Tkinter import END saveasfile = tkFileDialog.asksaveasfile() if not saveasfile: return alltext = self.text_input.get("1.0",END) saveasfile.write(alltext) def QuitCommand(self): self.master.quit() def ClearInputCommand(self): from Tkinter import END self.text_input.delete("1.0",END) def ClearOutputCommand(self): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.delete("1.0",END) self.text_output["state"] = DISABLED self.text_output.see(END) self.text_output.update() def ClearAllCommand(self): self.ClearInputCommand() self.ClearOutputCommand() def OutputFileCommand(self): import tkFileDialog outputfilename = tkFileDialog.asksaveasfilename() if sys.platform == 'win32' and len(outputfilename.split()) > 1: outputfilename = '"%s"' % outputfilename self.output_file_name = outputfilename def AboutCommand(self): self.OutputText('\n') self.OutputText('* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n') self.OutputText('\n') def UpdateOutput(self): if self.pypeOutput: text = self.pypeOutput.pop(0) self.output_stream.write(text) self.master.after(10,self.UpdateOutput) def RunPype(self,arguments): if not arguments: return if self.output_to_file.get() is not 'n' and self.output_file_name: self.output_stream.output_to_file = True self.output_stream.output_file = open(self.output_file_name,self.output_to_file.get()) else: self.output_stream.output_to_file = False self.queue.append(arguments) def GetWordUnderCursor(self): from Tkinter import CURRENT splitindex = self.text_input.index(CURRENT).split('.') line = self.text_input.get(splitindex[0]+".0",splitindex[0]+".end") wordstart = line.rfind(' ',0,int(splitindex[1])-1)+1 wordend = line.find(' ',int(splitindex[1])) if wordend == -1: wordend = len(line) word = line[wordstart:wordend] return word def GetWordIndex(self): startindex = self.text_input.index("insert-1c wordstart") endindex = self.text_input.index("insert-1c wordend") if self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == '-': startindex = self.text_input.index("insert-1c wordstart -2c") elif self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == ' ': startindex = self.text_input.index("insert-1c wordstart -1c") self.wordIndex[0] = startindex self.wordIndex[1] = endindex word = self.text_input.get(self.wordIndex[0],self.wordIndex[1]) return word def GetLogicalLine(self,physicallineid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallineid]] def GetLogicalLineRange(self,physicallinefirstid,physicallinelastid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallinefirstid]:indexes[physicallinelastid]+1] def GetAllLogicalLines(self): return self.GetLogicalLines()[1] def GetLogicalLines(self): from Tkinter import END physicallines = self.text_input.get("1.0",END).split('\n') lines = [] indexes = [0] * len(physicallines) lineid = 0 previousline = "" join = 0 for line in physicallines: if line.startswith('#'): if join: indexes[lineid] = indexes[lineid-1] elif join: if line.endswith('\\'): lines[-1] = lines[-1] + " " + line[:-1] join = 1 else: lines[-1] = lines[-1] + " " + line join = 0 indexes[lineid] = indexes[lineid-1] else: if line.endswith('\\'): join = 1 lines.append(line[:-1]) else: lines.append(line) join = 0 if lineid > 0: indexes[lineid] = indexes[lineid-1]+1 lineid += 1 return indexes, lines def GetLineUnderCursor(self): from Tkinter import INSERT currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1 return self.GetLogicalLine(currentlineid) def RunAllCommand(self): lines = self.GetAllLogicalLines() for line in lines: if line and line.strip(): self.RunPype(line) def RunLineCommand(self): line = self.GetLineUnderCursor() if line and line.strip(): self.RunPype(line) def RunSelectionCommand(self): from Tkinter import TclError, SEL_FIRST, SEL_LAST try: firstlineid = int(self.text_input.index(SEL_FIRST).split('.')[0]) - 1 lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1 lines = self.GetLogicalLineRange(firstlineid,lastlineid) for line in lines: self.RunPype(line) except TclError: pass def GetSuggestionsList(self,word): list = [] try: exec('import vmtkscripts') except ImportError: return None if word.startswith('--'): list = ['--pipe','--help'] elif word.startswith('-'): optionlist = [] scriptindex = self.text_input.search('vmtk',self.wordIndex[0],backwards=1) moduleName = self.text_input.get( scriptindex,scriptindex+' wordend' ) try: exec('import '+moduleName) exec('scriptObjectClassName = '+moduleName+'.'+moduleName) exec ('scriptObject = '+moduleName+'.'+scriptObjectClassName +'()') members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-'+member.OptionName) exec('list = [option for option in optionlist if option.count(word)]') except: return list else: exec('list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ]') return list def FillSuggestionsList(self,word): from Tkinter import END self.suggestionslist.delete(0,END) suggestions = self.GetSuggestionsList(word) for suggestion in suggestions: self.suggestionslist.insert(END,suggestion) def ReplaceTextCommand(self,word): self.text_input.delete(self.wordIndex[0],self.wordIndex[1]) self.text_input.insert(self.wordIndex[0],word) self.text_input.focus_set() def ShowHelpCommand(self): word = self.GetWordUnderCursor() self.OutputText(word) if word: self.RunPype(word+' --help') else: self.OutputText('Enter your vmtk Pype above and Run.\n') def AutoCompleteCommand(self): word = self.GetWordIndex() self.suggestionswindow.withdraw() if word: self.FillSuggestionsList(word) self.suggestionswindow.geometry("%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),self.text_output.winfo_rooty())) self.suggestionswindow.deiconify() self.suggestionswindow.lift() def InsertScriptName(self,scriptname): from Tkinter import INSERT self.text_input.insert(INSERT,scriptname+' ') def InsertFileName(self): from Tkinter import INSERT import tkFileDialog openfilename = tkFileDialog.askopenfilename() if not openfilename: return if len(openfilename.split()) > 1: openfilename = '"%s"' % openfilename self.text_input.insert(INSERT,openfilename+' ') def KeyPressHandler(self,event): if event.keysym == "Tab" : self.AutoCompleteCommand() self.suggestionslist.focus_set() self.suggestionslist.selection_set(0) return "break" else: self.text_input.focus_set() def TopKeyPressHandler(self,event): from Tkinter import ACTIVE, INSERT if event.keysym in ['Down','Up'] : self.suggestionslist.focus_set() elif event.keysym == "Return": word = self.suggestionslist.get(ACTIVE) self.ReplaceTextCommand(word) self.suggestionswindow.withdraw() self.text_input.focus_set() elif len(event.keysym) == 1 : self.suggestionswindow.withdraw() self.text_input.insert(INSERT,event.keysym) self.text_input.focus_set() else : self.suggestionswindow.withdraw() self.text_input.focus_set() def NewHandler(self,event): self.NewCommand() def OpenHandler(self,event): self.OpenCommand() def SaveHandler(self,event): self.SaveCommand() def InsertFileNameHandler(self,event): self.InsertFileName() return "break" def QuitHandler(self,event): self.QuitCommand() def ShowHelpHandler(self,event): self.ShowHelpCommand() def RunKeyboardHandler(self,event): from Tkinter import SEL_FIRST, TclError try: self.text_input.index(SEL_FIRST) self.RunSelectionCommand() except TclError: self.RunLineCommand() return "break" def RunAllHandler(self,event): self.RunAllCommand() def PopupHandler(self,event): try: self.popupmenu.tk_popup(event.x_root, event.y_root, 0) finally: self.popupmenu.grab_release() def OutputText(self,text): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.insert(END,text) self.text_output["state"] = DISABLED def BuildScriptMenu(self,parentmenu,modulename): from Tkinter import Menu menu = Menu(parentmenu,bd=1,activeborderwidth=0) try: exec('import '+ modulename) except ImportError: return None scriptnames = [] exec ('scriptnames = [scriptname for scriptname in '+modulename+'.__all__]') menulength = 20 for i in range(len(scriptnames)/menulength+1): subscriptnames = scriptnames[i*menulength:(i+1)*menulength] if not subscriptnames: break submenu = Menu(menu,bd=1,activeborderwidth=0) menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu) for scriptname in subscriptnames: callback = CallbackShim(self.InsertScriptName,scriptname) submenu.add_command(label=scriptname,command=callback) return menu def BuildMainFrame(self): from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED menu = Menu(self.master,activeborderwidth=0,bd=0) self.master.config(menu=menu) filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="File", underline=0, menu=filemenu) filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand) filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand) filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand) filemenu.add_separator() filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand) self.log_on = IntVar() self.log_on.set(1) self.output_to_file = StringVar() self.output_to_file.set('n') scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) modulenames = ['vmtkscripts'] for modulename in modulenames: scriptsubmenu = self.BuildScriptMenu(menu,modulename) if scriptsubmenu: scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu) editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Edit",underline=0, menu=editmenu) editmenu.add_cascade(label="Insert script",menu=scriptmenu) editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName) editmenu.add_separator() editmenu.add_command(label="Clear input", command=self.ClearInputCommand) editmenu.add_command(label="Clear output", command=self.ClearOutputCommand) editmenu.add_command(label="Clear all", command=self.ClearAllCommand) editmenu.add_separator() editmenu.add_checkbutton(label="Log", variable=self.log_on) editmenu.add_separator() editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n') editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w') editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a') editmenu.add_command(label="Output file...", command=self.OutputFileCommand) runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Run", underline=0, menu=runmenu) runmenu.add_command(label="Run all", command=self.RunAllCommand) runmenu.add_command(label="Run current line", command=self.RunLineCommand) runmenu.add_command(label="Run selection", command=self.RunSelectionCommand) helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0) menu.add_cascade(label="Help", underline=0, menu=helpmenu) helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand) helpmenu.add_command(label="About", underline=0, command=self.AboutCommand) self.master.bind("<Control-KeyPress-q>", self.QuitHandler) self.master.bind("<Control-KeyPress-n>", self.NewHandler) self.master.bind("<Control-KeyPress-o>", self.OpenHandler) self.master.bind("<Control-KeyPress-s>", self.SaveHandler) self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler) self.master.bind("<KeyPress-F1>", self.ShowHelpHandler) self.master.bind("<KeyPress>", self.KeyPressHandler) self.wordIndex = ['1.0','1.0'] self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True) self.suggestionswindow.overrideredirect(1) self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9) self.suggestionslist.insert(END,"foo") self.suggestionslist.pack(side=TOP,fill=X) self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler) self.suggestionswindow.withdraw() self.master.rowconfigure(0,weight=1) self.master.columnconfigure(0,weight=1) content = Frame(self.master,bd=0,padx=2,pady=2) content.grid(row=0,column=0,sticky=N+S+W+E) content.rowconfigure(0,weight=1,minsize=50) content.rowconfigure(1,weight=0) content.columnconfigure(0,weight=1) panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True) panes.grid(row=0,column=0,sticky=N+S+W+E) frame1 = Frame(panes,bd=0) frame1.grid(row=0,column=0,sticky=N+S+W+E) frame1.columnconfigure(0,weight=1) frame1.columnconfigure(1,weight=0) frame1.rowconfigure(0,weight=1) panes.add(frame1,height=300,minsize=20) frame2 = Frame(panes,bd=0) frame2.grid(row=1,column=0,sticky=N+S+W+E) frame2.columnconfigure(0,weight=1) frame2.columnconfigure(1,weight=0) frame2.rowconfigure(0,weight=1) panes.add(frame2,minsize=20) self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0) self.text_input.bind("<KeyPress>", self.KeyPressHandler) self.text_input.bind("<Button-3>", self.PopupHandler) self.text_input.bind("<Control-Return>", self.RunKeyboardHandler) self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview) self.text_input["yscrollcommand"] = self.input_scrollbar.set self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0) self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview) self.text_output["yscrollcommand"] = self.output_scrollbar.set self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0) self.text_input.focus_set() self.text_input.grid(row=0,column=0,sticky=N+S+W+E) self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E) self.text_output.grid(row=0,column=0,sticky=N+S+W+E) self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E) self.text_entry.grid(row=1,column=0,sticky=N+S+W+E) self.popupmenu = Menu(self.text_input, tearoff=1, bd=0) self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand) self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu) self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName) self.popupmenu.add_separator() self.popupmenu.add_command(label="Run all", command=self.RunAllCommand) self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand) self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand) self.output_stream = TkPadOutputStream(self.text_output) self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
class Editor(object): """ Finestra per l'editor di condice assembly """ def __init__(self, master, calcolatore): """ Inizializza i frame della finestra dell'Editor """ self.master = master self.CD = calcolatore # Codice Assembly self.codice = LabelFrame( self.master, text='Codice Assembly', relief=RIDGE, borderwidth=5, labelanchor='n', pady=5) self.codice.rowconfigure(0, weight=1) self.codice.columnconfigure(0, weight=1) self.codice.grid( row=1, column=0, rowspan=3, columnspan=5, sticky=W + E + N + S) self.menubar = Menu(self.master) self.create_widgets(self.menubar) def create_widgets(self, menubar): """ Crea il layout del programma, finestra dell'Editor """ # Menu self.filemenu = Menu(menubar, tearoff=0) self.filemenu.add_command(label='Apri', command=self.aprifile) self.filemenu.add_command(label='Salva', command=self.salvafile) self.filemenu.add_command(label='Cancella', command=self.cancella) self.filemenu.add_separator() self.filemenu.add_command(label='Esci', command=self.exit) menubar.add_cascade(label='Opzioni', menu=self.filemenu) self.master.config(menu=self.menubar) self.helpmenu = Menu(menubar, tearoff=0) self.helpmenu.add_command(label='Informazioni', command=self.infor) self.helpmenu.add_command(label='Legenda', command=self.leg) self.helpmenu.add_command(label='Guida', command=self.guida) menubar.add_cascade(label='Aiuto', menu=self.helpmenu) # Codice Assembly self.Inserisci = Text(self.codice, width=50, height=30, wrap=WORD) self.Inserisciscrollbar = Scrollbar(self.codice) self.Inserisciscrollbar.config(command=self.Inserisci.yview) self.Inserisci.config(yscrollcommand=self.Inserisciscrollbar.set) self.Inserisciscrollbar.grid(row=0, column=1, sticky=N + S) self.Inserisci.grid(row=0, column=0, sticky=W) def exit(self): """ Esce dal programma """ if askquestion('Exit', 'Sicuro di voler uscire?') == YES: self.master.quit() self.master.destroy() else: showinfo( 'Suggerimento', """Forse e' meglio fare una pausa!""", icon=WARNING) def aprifile(self): """ Apre un file assembly e lo mostra a video per essere modificato """ path = askopenfilename(title='Apri codice assembly', filetypes=[('Assembly', '.asm'), ('Testo', '.txt'), ('All', '*')]) if path != '': file = open(path, 'r') temp = file.read() self.Inserisci.delete(1.0, END) self.Inserisci.insert(INSERT, temp.decode('ascii', 'ignore')) file.close() def cancella(self): """ Cancella l'attuale file assembly caricato """ if askquestion('Cancella', 'Si vuole cancellare tutto il codice assembly?') == YES: self.Inserisci.delete(1.0, END) def salvafile(self): """ Salva il file assembly su cui si sta lavorando """ contenuto = self.Inserisci.get(1.0, END) contenuto = contenuto.encode('ascii', 'ignore') path = asksaveasfilename(title='Salva codice assembly', defaultextension=[ ('Assembly', '.asm'), ('Testo', '.txt'), ('All', '*')], filetypes=[('Assembly', '.asm'), ('Testo', '.txt'), ('All', '*')]) print path if path != '': file = open(path, 'w') file.write(str(contenuto)) file.close() @staticmethod def infor(): """ Visualizza le informazioni riguardante il programma """ nome = """pdp8 emulator""" stringa = """ Pdp8 Emulator °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°° Version = 1.6.2 Tested with = python 2.6 & 2.7 ------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015 Mirco Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------- Contact: [email protected] Collaborators : Walter Valentini """ showinfo(nome, stringa) @staticmethod def leg(): """ Visualizza le informazioni riguardanti colori """ nome = """pdp8 Legenda""" stringa = """ Rosso = indirizzo puntato da PC Giallo = indirizzo puntato da MAR Verde = ultima istruzione eseguita """ showinfo(nome, stringa) @staticmethod def guida(): """ Piccola guida """ nome = """pdp8 Guida""" stringa = """ LOAD = Carica il assembly nella memoria del Calcolatore Didattico (CD). STEP = Avanza del numero di step indicato (di default 1). Uno step equivale all'esecuzione di una singola istruzione. mini STEP = Esegue un singolo ciclo in base alle variabili F ed R dell'unità di controllo. micro STEP = Esegue ogni singola microistruzione. Set n STEP = Setta il numero di step. Set Delay = Setta il tempo di aggiornamento del CD. START = Avvia il CD, ma non l'esecuzione del codice. Per eseguire il codice, utilizzare step o esegui una volta avviata la macchina. RESET = Resetta il CD allo stato iniziale. STOP = Ferma il CD e quindi anche l'esecuzione del codice. BREAK = Aggiunge o toglie un break alla cella indicata in esadecimale. CONTINUA = Continua l'esecuzione del programma dopo un break. Equivale a premere in sequenza START ed ESEGUI. ESEGUI = Esegue il codice fino all'istruzione HLT, che arresta la macchina. """ showinfo(nome, stringa)
def __init__(self, filename, parentnotebook): """Create a new EditTab Argument filename -- name and path to the file being edited parentnotebook -- the NoteBook in which this tab will be added """ Frame.__init__(self) self._filename = filename self._parentnotebook = parentnotebook self._inputs = [] self.path = os.path.dirname(filename) self._dirty = False parentnotebook.add(self, state='normal') self._setLabel() #Set up GUI self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) vscroll = Scrollbar(self, orient=VERTICAL) self._vscroll = vscroll vscroll.grid(row=0, column=1, sticky=N + S) hscroll = Scrollbar(self, orient=HORIZONTAL) self._hscroll = hscroll hscroll.grid(row=1, column=0, sticky=E + W) canvas = Canvas(self, yscrollcommand=vscroll.set, xscrollcommand=hscroll.set) self._canvas = canvas canvas.grid(row=0, column=0, padx=5, pady=5, sticky=NSEW) vscroll['command'] = canvas.yview hscroll['command'] = canvas.xview scrollframe = Frame(canvas) self._scrollframe = scrollframe canvas.create_window(0, 0, window=scrollframe, anchor=N + W) scrollframe.rowconfigure(0, weight=1) scrollframe.columnconfigure(0, weight=1) self._mainframe = Frame(scrollframe) self._mainframe.grid(row=0, column=0, padx=5, pady=5, sticky=NSEW) cf = Frame(scrollframe) self._control_frame = cf cf.grid(row=1, column=0, padx=5, pady=5, sticky=E) b = Button(cf, text=lang[lng.txtCopyImages], command=self._ehCopyImages) self._btnCopy = b b.grid(row=0, column=0, padx=5, pady=5) b = Button(cf, text=lang[lng.txtSave], command=self._ehSave, state=DISABLED) self._btnSave = b b.grid(row=0, column=1, padx=5, pady=5) b = Button(cf, text=lang[lng.txtClose], command=self._ehClose) b.grid(row=0, column=2, padx=5, pady=5) parentnotebook.after_idle(self._setCanvas)
def __init__(self, ncffile, options): try: from Tkinter import Checkbutton, Frame, Label, Scrollbar from Tkinter import Listbox, Button, IntVar, Tk, VERTICAL from Tkinter import EXTENDED, END, N, S, SINGLE, Entry from Tkinter import StringVar, Text, DISABLED, LEFT except Exception: try: from tkinter import Checkbutton, Frame, Label, Scrollbar from tkinter import Listbox, Button, IntVar, Tk, VERTICAL from tkinter import EXTENDED, END, N, S, SINGLE, Entry from tkinter import StringVar, Text, DISABLED, LEFT except Exception: warn('tkinter unavailable') master = self.root = Tk() self.ncffile = ncffile self.options = options self.plotted_variables = set() frame = Frame(master) frame.grid(row=0) codeframe = Frame(master) codeframe.grid(row=1) metaframe = Frame(master) metaframe.grid(row=2) goframe = Frame(frame) goframe.grid(column=3, row=1) var_label = Label(frame, text='Select Variable') var_label.grid(column=0, row=0) var_scrollbar = Scrollbar(frame, orient=VERTICAL) var_scrollbar.grid(column=1, row=1, sticky=N + S) self.var = Listbox(frame, selectmode=EXTENDED, exportselection=0, yscrollcommand=var_scrollbar.set) self.var.grid(column=0, row=1) var_scrollbar.config(command=self.var.yview) what_to_do = Label(frame, text='Execute') what_to_do.grid(column=2, row=0) self.method_list = Listbox(frame, selectmode=SINGLE, exportselection=0) self.method_list.grid(column=2, row=1) self.pre_txt = StringVar() pre_label = Label(codeframe, text='Before any figures, execute code') self.pre_txt.set(_pre_code) pre_label.grid(row=2, sticky='W') self.pre = Entry(codeframe, width=120, textvariable=self.pre_txt) self.pre.grid(row=3, sticky='E') self.before_txt = StringVar() self.before_txt.set(_before_code) before_label = Label( codeframe, text='Before each figure, execute code') before_label.grid(row=4, sticky='W') self.before = Entry(codeframe, width=120, textvariable=self.before_txt) self.before.grid(row=5, sticky='E') self.after_txt = StringVar() self.after_txt.set(_after_code) after_label = Label(codeframe, text='After each figure, execute code') after_label.grid(row=6, sticky='W') self.after = Entry(codeframe, width=120, textvariable=self.after_txt) self.after.grid(row=7, sticky='E') self.post_txt = StringVar() self.post_txt.set(_post_code) post_label = Label(codeframe, text='After all figures, execute code') post_label.grid(row=8, sticky='W') self.post = Entry(codeframe, width=120, textvariable=self.post_txt) self.post.grid(row=9, sticky='E') options_label = Label(goframe, text='Options:') options_label.grid(column=0, row=1, sticky='W') self.logscale = IntVar() self.logscale.set(0) c = Checkbutton(goframe, text="log-scale?", variable=self.logscale) c.grid(column=0, row=2, sticky='W') self.coastlines = IntVar() self.coastlines.set(_coastlines_opt) coastlines = Checkbutton( goframe, text="coastlines?", variable=self.coastlines, justify=LEFT) coastlines.grid(column=0, row=3, sticky='W') self.countries = IntVar() self.countries.set(_countries_opt) countries = Checkbutton( goframe, text="countries?", variable=self.countries, justify=LEFT) countries.grid(column=0, row=4, sticky='W') self.states = IntVar() self.states.set(_states_opt) states = Checkbutton(goframe, text="states?", variable=self.states, justify=LEFT) states.grid(column=0, row=5, sticky='W') self.counties = IntVar() self.counties.set(_counties_opt) counties = Checkbutton(goframe, text="counties?", variable=self.counties, justify=LEFT) counties.grid(column=0, row=6, sticky='W') self.execute_button = Button( goframe, text="Make Figure", command=self.execute) self.execute_button.grid(row=0, column=0, sticky='W') self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot'] method_labels = ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)'] for method in method_labels: self.method_list.insert(END, method) var_keys = [k for k, v in self.ncffile.variables.items() if k not in _coordkeys] var_keys.sort() self.vars = [] for spc in var_keys: self.var.insert(END, spc) self.vars.append(spc) meta_label = Label(metaframe, text='Common Data Language Header:') meta_label.grid(column=0, row=0, sticky='W') meta_scrollbar = Scrollbar(metaframe, orient=VERTICAL) meta_scrollbar.grid(column=1, row=1, sticky=N + S) self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand=meta_scrollbar.set) self.meta.grid(column=0, row=1, sticky='W') from PseudoNetCDF.pncdump import pncdump try: from StringIO import StringIO except ImportError: from io import StringIO pdump = StringIO("") pncdump(self.ncffile, header=True, outfile=pdump, ) pdump.seek(0, 0) self.meta.insert(END, pdump.read()) self.meta.config(state=DISABLED) help = Button(goframe, text='Help', command=self.help) help.grid(column=0, row=7) quit = Button(goframe, text='Quit', command=self.quit) quit.grid(column=0, row=8) master.mainloop()
def initUI(self): global scriptdir, calldir global dnd global URLentry global savedirentry troot = self.parent # self.parent.master # was self.parent; # now parent is child of root troot.title("youtube-dl Tkinter/TkDND GUI") #~ self.pack(fill=BOTH, expand=1) # just a reference here: self.URLentry = URLentry self.savedirentry = savedirentry self.lfname = "" self.outdir = scriptdir savedirentry.delete(0, END) savedirentry.insert(0, self.outdir) #create a grid 5x4 in to which we will place elements. self.columnconfigure(1, weight=0) self.columnconfigure(2, weight=1) self.columnconfigure(3, weight=0) self.columnconfigure(4, weight=0) self.columnconfigure(5, weight=0) self.rowconfigure(1, weight=0) self.rowconfigure(2, weight=1) self.rowconfigure(3, weight=0) #create the main text are with scrollbars xscrollbar = Scrollbar(self, orient=HORIZONTAL) xscrollbar.grid(row=3, column=1, columnspan=4, sticky=E + W) yscrollbar = Scrollbar(self, orient=VERTICAL) yscrollbar.grid(row=2, column=5, sticky=N + S) self.textarea = Text(self, wrap=NONE, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set) self.textarea.grid(row=2, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) xscrollbar.config(command=self.textarea.xview) yscrollbar.config(command=self.textarea.yview) #create the buttons/checkboxes to go along the bottom self.clearButton = Button(self, text="Clear") self.clearButton.grid(row=1, column=1, padx=5, pady=5, sticky=W) self.clearButton.bind("<ButtonRelease-1>", self.clearText) self.delButton = Button(self, text="Del.Files") self.delButton.grid(row=1, column=2, padx=5, pady=5, sticky=W) self.delButton.bind("<ButtonRelease-1>", self.deleteFiles) self.runbutton = Button(self, text="Run/Call") self.runbutton.grid(row=1, column=3, padx=5, pady=5) self.runbutton.bind("<ButtonRelease-1>", self.runScript) self.stopbutton = Button(self, text="Stop") self.stopbutton.grid(row=1, column=4, padx=5, pady=5) self.stopbutton.bind("<ButtonRelease-1>", self.stopScript) #tags are used to colorise the text added to the text widget. # see self.addTtext and self.tagsForLine self.textarea.tag_config("errorstring", foreground="#CC0000") self.textarea.tag_config("infostring", foreground="#008800") self.addText("Path A: " + calldir + "\n", ("infostring", )) self.addText("(chdir)" + "\n", ("infostring", )) os.chdir(scriptdir) self.addText("Path B: " + os.getcwd() + "\n\n", ("infostring", )) self.addText("DL command is: " + " ".join(scriptcall) + "\n", ("infostring", )) self.addText("Player command is: " + " ".join(playcommand) + "\n\n", ("infostring", ))
def initUI(self): self.frame = Frame(self.parent, relief=RAISED,borderwidth=1) #panel with the information to be introduced #self.grid(row=0,column=0) self.position = PanelInformation.PanelInformation(self.frame) self.position.getFrame().grid(row=0,column=0) self.position.setLabelXLabel("Position X:") self.position.setLabelYLabel("Position Y:") self.position.setLabelThetaLabel("Position Theta:") self.velocity = PanelInformation.PanelInformation(self.frame) self.velocity.getFrame().grid(row=1,column=0) self.velocity.setLabelXLabel("Walk Shoulder:") self.velocity.setLabelYLabel("Walk torso:") self.velocity.setLabelThetaLabel("Pose:") #panel for the emotion intensity self.frameIntensity = Frame(self.frame, relief=RAISED,borderwidth=1) self.frameIntensity.grid(row = 4, column = 0) self.labelIntensity = Label(self.frameIntensity,text="Intensity:") self.labelIntensity.grid(row=0,column=0) self.intensity = Scale(self.frameIntensity, from_=0, to = 1,command=self.onScale) self.intensity.grid(row = 1, column = 0) self.var = IntVar() self.labelInfoIntensity = Label(self.frameIntensity, text=0, textvariable=self.var) self.labelInfoIntensity.grid(row = 2, column = 0) #panel with the robot's information self.positionInfo = PanelInformation.PanelInformation(self.frame) self.positionInfo.setDisableEntry() self.positionInfo.getFrame().grid(row=0,column=2) self.positionInfo.setLabelXLabel("Position X:") self.positionInfo.setLabelYLabel("Position Y:") self.positionInfo.setLabelThetaLabel("Position Theta:") self.velocityInfo = PanelInformation.PanelInformation(self.frame) self.velocityInfo.setDisableEntry() self.velocityInfo.getFrame().grid(row=1,column=2) self.velocityInfo.setLabelXLabel("Velocity X:") self.velocityInfo.setLabelYLabel("Velocity Y:") self.velocityInfo.setLabelThetaLabel("Velocity Theta:") #emotions and actions self.frameEmotionAction = Frame(self.frame, relief=RAISED,borderwidth=1) self.frameEmotionAction.grid(row=2,column=0,columnspan=3) self.labelEmotion = Label(self.frameEmotionAction,text="Emotion:") self.labelEmotion.grid(row=0,column=0) scrollbar = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar.grid(row=0,column=3) self.listEmotion = Listbox(self.frameEmotionAction,height=4) self.listEmotion.grid(row=0,column=2) self.listEmotion.bind("<<ListboxSelect>>", self.onSelectEmotion) #the new emotions should be added here self.emotions = ['neutral','angry','happy','sad','fear','content'] for item in self.emotions: self.listEmotion.insert(END,item) self.listEmotion.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.listEmotion.yview) self.labelAction = Label(self.frameEmotionAction,text="Action:") self.labelAction.grid(row=0,column=4) scrollbar2 = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar2.grid(row=0,column=6) self.listAction = Listbox(self.frameEmotionAction,height=4) self.listAction.grid(row=0,column=5) #the new actions should be added here self.actions = ['not_do_anything','oscillate_shoulder','oscillate_body','move_shoulder','move_body','move_torso','oscillate_torso','walk'] for item in self.actions: self.listAction.insert(END,item) self.listAction.config(yscrollcommand=scrollbar2.set) self.listAction.bind("<<ListboxSelect>>", self.onSelectAction) scrollbar2.config(command=self.listAction.yview) self.actionSelected = "do_nothing" self.emotionSelected = "neutral"
def __init__(self, ncffile, options): master = self.root = Tk() self.ncffile = ncffile self.options = options self.plotted_variables = set() frame = Frame(master) frame.grid(row = 0) codeframe = Frame(master) codeframe.grid(row = 1) metaframe = Frame(master) metaframe.grid(row = 2) goframe = Frame(frame) goframe.grid(column = 3, row = 1) var_label = Label(frame, text = 'Select Variable') var_label.grid(column = 0, row = 0) var_scrollbar = Scrollbar(frame, orient = VERTICAL) var_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.var = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = var_scrollbar.set) self.var.grid(column = 0, row = 1) var_scrollbar.config(command = self.var.yview) what_to_do = Label(frame, text = 'Execute') what_to_do.grid(column = 2, row = 0) self.method_list = Listbox(frame, selectmode = SINGLE, exportselection = 0) self.method_list.grid(column = 2, row = 1) self.pre_txt = StringVar() pre_label = Label(codeframe, text = 'Before any figures, execute code') self.pre_txt.set(_pre_code) pre_label.grid(row = 2, sticky = 'W') self.pre = Entry(codeframe, width = 120, textvariable = self.pre_txt) self.pre.grid(row =3, sticky = 'E') self.before_txt = StringVar() self.before_txt.set(_before_code) before_label = Label(codeframe, text = 'Before each figure, execute code') before_label.grid(row = 4, sticky = 'W') self.before = Entry(codeframe, width = 120, textvariable = self.before_txt) self.before.grid(row =5, sticky = 'E') self.after_txt = StringVar() self.after_txt.set(_after_code) after_label = Label(codeframe, text = 'After each figure, execute code') after_label.grid(row = 6, sticky = 'W') self.after = Entry(codeframe, width = 120, textvariable = self.after_txt) self.after.grid(row =7, sticky = 'E') self.post_txt = StringVar() self.post_txt.set(_post_code) post_label = Label(codeframe, text = 'After all figures, execute code') post_label.grid(row = 8, sticky = 'W') self.post = Entry(codeframe, width = 120, textvariable = self.post_txt) self.post.grid(row = 9, sticky = 'E') options_label = Label(goframe, text = 'Options:') options_label.grid(column = 0, row = 1, sticky = 'W') self.logscale = IntVar() self.logscale.set(0) c = Checkbutton(goframe, text = "log-scale?", variable = self.logscale) c.grid(column = 0, row = 2, sticky = 'W') self.coastlines = IntVar() self.coastlines.set(_coastlines_opt) coastlines = Checkbutton(goframe, text = "coastlines?", variable = self.coastlines, justify = LEFT) coastlines.grid(column = 0, row = 3, sticky = 'W') self.countries = IntVar() self.countries.set(_countries_opt) countries = Checkbutton(goframe, text = "countries?", variable = self.countries, justify = LEFT) countries.grid(column = 0, row = 4, sticky = 'W') self.states = IntVar() self.states.set(_states_opt) states = Checkbutton(goframe, text = "states?", variable = self.states, justify = LEFT) states.grid(column = 0, row = 5, sticky = 'W') self.counties = IntVar() self.counties.set(_counties_opt) counties = Checkbutton(goframe, text = "counties?", variable = self.counties, justify = LEFT) counties.grid(column = 0, row = 6, sticky = 'W') self.execute_button = Button(goframe, text = "Make Figure", command = self.execute) self.execute_button.grid(row = 0, column = 0, sticky = 'W') self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot'] method_labels= ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)'] for method in method_labels: self.method_list.insert(END, method) var_keys = [k for k, v in self.ncffile.variables.items() if k not in ('time', 'latitude', 'longitude', 'latitude_bounds', 'longitude_bounds', 'time_bounds', 'tau0', 'tau1', 'TFLAG')] var_keys.sort() self.vars = [] for spc in var_keys: self.var.insert(END, spc) self.vars.append(spc) meta_label = Label(metaframe, text = 'Common Data Language Header:') meta_label.grid(column = 0, row = 0, sticky = 'W') meta_scrollbar = Scrollbar(metaframe, orient = VERTICAL) meta_scrollbar.grid(column = 1, row = 1, sticky = N + S) self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand = meta_scrollbar.set) self.meta.grid(column = 0, row = 1, sticky = 'W') from PseudoNetCDF.pncdump import pncdump try: from StringIO import StringIO except ImportError: from io import StringIO pdump = StringIO("") try: name = ', '.join(options.ifile) except: name = 'ifile' pncdump(self.ncffile, header = True, outfile = pdump, ) pdump.seek(0, 0) self.meta.insert(END, pdump.read()) self.meta.config(state=DISABLED) help = Button(goframe, text = 'Help', command = self.help) help.grid(column = 0, row = 7) quit = Button(goframe, text = 'Quit', command = self.quit) quit.grid(column = 0, row = 8) master.mainloop()
def build_dlg(self): top = self.top buttons = self.create_std_buttons(top) buttons.grid(row=3, column=4, columnspan=2, sticky="news") self.sample = FontPreview(top) self.sample.grid(column=0, row=3, columnspan=4, sticky="news") # XXX: the background color of the sample text should be # configurable label = Label(top, text=_("Font Family:"), anchor=W) label.grid(column=0, row=0, columnspan=2, sticky="ew") sb_vert = Scrollbar(top, takefocus=0) sb_vert.grid(column=1, row=1, rowspan=2, sticky="news") family_list = UpdatedListbox(top, name='families', height=8) family_list.grid(column=0, row=1, rowspan=2, sticky="news") family_list.Subscribe(SELECTION, self.family_selected) sb_vert['command'] = (family_list, 'yview') family_list['yscrollcommand'] = (sb_vert, 'set') self.family_list = family_list label = Label(top, text=_("Font Style:"), anchor=W) label.grid(column=2, row=0, sticky="ew") sb_vert = Scrollbar(top, takefocus=0) sb_vert.grid(column=3, row=1, rowspan=2, sticky="news") self.font_attr_list = UpdatedListbox(top, name='weights', height=4, width=15) self.font_attr_list.grid(column=2, row=1, rowspan=2, sticky="news") self.font_attr_list.Subscribe(SELECTION, self.attr_selected) sb_vert['command'] = (self.font_attr_list, 'yview') self.font_attr_list['yscrollcommand'] = (sb_vert, 'set') label = Label(top, text=_("Size:"), anchor=W) label.grid(column=4, row=0, columnspan=2, sticky="ew") frame = Frame(top) frame.grid(column=4, row=1, columnspan=2, sticky='ew') self.var_size = DoubleVar(top) scroll = MiniScroller(frame, variable=self.var_size, min=0.0, max=None, step=1) scroll.pack(side=RIGHT, fill=Y) self.size_entry = MyEntry(frame, textvariable=self.var_size, width=4, command=self.apply_size, justify=RIGHT) self.size_entry.pack(side=LEFT, expand=1, fill=BOTH) sb_vert = Scrollbar(top, takefocus=0) sb_vert.grid(column=5, row=2, sticky="news") self.size_list = UpdatedListbox(top, name='sizes', width=4, height=5) self.size_list.grid(column=4, row=2, sticky="news") self.size_list.Subscribe(SELECTION, self.size_selected) self.size_list.SetList(std_sizes) sb_vert['command'] = (self.size_list, 'yview') self.size_list['yscrollcommand'] = (sb_vert, 'set') top.columnconfigure(0, weight=1000) top.columnconfigure(4, weight=1) top.rowconfigure(2, weight=1)
def CreateWidgets(self): frameMain = Frame(self,borderwidth=2,relief=SUNKEN) frameMain.pack(side=TOP,expand=TRUE,fill=BOTH) frameButtons=Frame(self) frameButtons.pack(side=BOTTOM,fill=X) self.buttonOK = Button(frameButtons,text='OK', width=8,command=self.OK) self.buttonOK.grid(row=0,column=0,padx=5,pady=5) self.buttonCancel = Button(frameButtons,text='Cancel', width=8,command=self.Cancel) self.buttonCancel.grid(row=0,column=1,padx=5,pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain,command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '"+self.action+"' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT, textvariable=self.keyString,relief=GROOVE,borderwidth=2) labelKeysBasic.pack(ipadx=5,ipady=5,fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check=Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label,variable=variable,onvalue=modifier,offvalue='') check.grid(row=0,column=column,padx=2,sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W) self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected) self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS) scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS) self.buttonClear=Button(self.frameControlsBasic, text='Clear Keys',command=self.ClearKeySeq) self.buttonClear.grid(row=2,column=0,columnspan=4) labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT, text="Enter new binding(s) for '"+self.action+"' :\n"+ "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)
class GcFrame(LabelFrame): def __init__(self, root, filename, contents, settings, logger, *arg): LabelFrame.__init__(self, root, *arg, text="gcode Viewer") self.label = Label(self) self.canvas = Canvas(self, width=settings.buildarea[0]*SCALE, height=settings.buildarea[1]*SCALE, bd=2, relief=RIDGE, bg="black") self.canvas.config(takefocus="1") self.root = root self.settings = settings self.buildarea = settings.buildarea self.log = logger self.zoom = 1 self.offsetx = 0 self.offsety = 0 self.movestartx = 0 self.movestarty = 0 self.sb = Scrollbar(self) self.sb.config(command=self.scroll) self.sb.set(0.0, 1.0) self.sbslidersize = 1.0 self.syncwithprint = IntVar() self.syncwithprint.set(1) self.bZoomOut = Button(self, text="-", width=3, command=self.doZoomOut) self.bZoomIn = Button(self, text="+", width=3, command=self.doZoomIn) self.cb = Checkbutton(self, text="Sync view with print", variable=self.syncwithprint, command=self.syncClick) self.bReset = Button(self, text="Reset View", command=self.pressReset) self.canvas.bind("<Button-1>", self.startMove); self.canvas.bind("<B1-Motion>", self.continueMove); self.canvas.bind("<MouseWheel>", self.mouseWheel); self.canvas.bind("<Button-4>", self.mouseWheel); self.canvas.bind("<Button-5>", self.mouseWheel); self.canvas.bind("<Shift-MouseWheel>", self.mouseWheelZoom); self.canvas.bind("<Shift-Button-4>", self.mouseWheelZoom); self.canvas.bind("<Shift-Button-5>", self.mouseWheelZoom); self.label.grid(row=1, column=1, columnspan=5) self.canvas.grid(row=2,column=1,columnspan=5) self.sb.grid(row=2, column=6, sticky=N+S) self.bZoomOut.grid(row=3, column=1, sticky=E) self.bZoomIn.grid(row=3, column=2, sticky=W) self.cb.grid(row=3, column=3, columnspan=2) self.bReset.grid(row=3, column=5, columnspan=2) self.currentlayer = None self.currentdrawn = None self.currentlx = None self.layercount = 0 self.filename = None self.printprogress = 0 self.minline = 0 self.maxline = 0 self.drawGrid() self.model = Model() if filename != None: self.loadFile(filename, contents) #self.drawLayer(self.currentlayer) def getPrintStartLine(self): return self.model.getPrintStartLine() def pressReset(self): self.resetView() def startMove(self, e): self.canvas.focus_set() self.movestartx = e.x self.movestarty = e.y self.moveoffsetx = self.offsetx self.moveoffsety = self.offsety def continueMove(self, e): dx = e.x - self.movestartx dy = e.y - self.movestarty self.offsetx = self.moveoffsetx - dx/(2*self.zoom) self.offsety = self.moveoffsety - dy/(2*self.zoom) self.drawCanvas() def updatePrintProgress(self, n, restart=False): if n == 0: self.printprogress = 0 if self.syncwithprint.get() == 1: if restart: self.currentLayer = self.model.bottomLayer() self.currentdrawn = None self.currentlx = 0 self.setSliderPos() self.drawLayer(self.currentlayer) return if n <= self.printprogress: return ll = self.model.findLayersbyLineNo(self.printprogress, n) if len(ll) == 0: return self.printprogress = n if self.syncwithprint.get() == 1: if self.currentlayer != ll[-1]: self.currentlayer = ll[-1] self.currentlx = self.model.getLayerNumber(self.currentlayer) self.drawLayer(self.currentlayer) self.setSliderPos() else: self.drawOneLayer(self.currentlayer, updateonly=True) else: if self.currentlayer in ll: self.drawOneLayer(self.currentlayer, updateonly=True) def scroll(self, *a): if self.currentlx == None: self.currentlx = 0 if a[0] == "scroll": nlx = self.currentlx - int(a[1]) if nlx < 0: nlx = 0 elif nlx >= self.model.countLayers(): nlx = self.model.countLayers()-1 elif a[0] == "moveto": pos = 1.0 - float(a[1]) nlx = int(pos / self.sbslidersize) - 1 if nlx < 0: nlx = 0 elif nlx >= self.model.countLayers(): nlx = self.model.countLayers()-1 else: return self.currentlx = nlx self.currentlayer = self.model.getLayerName(nlx) self.drawLayer(self.currentlayer) self.setSliderPos() def setSliderPos(self): if self.currentlx == None: self.currentlx = 0 sbpos = 1.0 - (self.currentlx * self.sbslidersize) - self.sbslidersize if sbpos < 0.0: sbpos = 0.0 self.sb.set(sbpos, sbpos+self.sbslidersize) def syncClick(self): if self.syncwithprint.get() == 1: self.updatePrintProgress(self.printprogress) def mouseWheel(self, e): if e.num == 5 or e.keycode == -120: #scroll down self.scroll("scroll", 1) elif e.num == 4 or e.keycode == 120: #scroll up self.scroll("scroll", -1) def mouseWheelZoom(self, e): if e.num == 5 or e.keycode == -120: #zoom in self.doZoomIn() elif e.num == 4 or e.keycode == 120: #zoom out if self.zoom > 1: self.doZoomOut() def doZoomIn(self): cw = self.buildarea[0]/self.zoom ch = self.buildarea[1]/self.zoom self.zoom += 1 nw = self.buildarea[0]/self.zoom nh = self.buildarea[1]/self.zoom self.offsetx += (cw-nw)/2 self.offsety += (ch-nh)/2 self.drawCanvas() def doZoomOut(self): if self.zoom > 1: cw = self.buildarea[0]/self.zoom ch = self.buildarea[1]/self.zoom self.zoom -= 1 if self.zoom < 1: self.zoom = 1 nw = self.buildarea[0]/self.zoom nh = self.buildarea[1]/self.zoom self.offsetx -= (nw-cw)/2 self.offsety -= (nh-ch)/2 self.drawCanvas() def loadFile(self, filename, contents): self.filename = filename self.model.addFile(contents) self.currentlayer = self.model.bottomLayer() self.currentlx = 0 self.currentdrawn = None self.printprogress = 0 self.layercount = self.model.countLayers() self.drawLayer(self.currentlayer) if self.layercount > 0: self.sbslidersize = 1.0 / self.layercount self.setSliderPos() def getLayerNumberByHeight(self, z): return self.model.getLayerNumberByHeight(z) def resetView(self): self.zoom = 1 self.offsety = 0 self.offsetx = 0 self.drawCanvas() def drawCanvas(self): self.currentdrawn = None self.drawGrid() self.drawLayer(self.currentlayer) self.setSliderPos() def drawGrid(self): self.canvas.delete("GRID") ltGrey = "#424242" dkGrey = "#404040" yleft = (0 - self.offsety)*self.zoom*SCALE if yleft < 0: yleft = 0 yright = (self.buildarea[1] - self.offsety)*self.zoom*SCALE if yright > self.buildarea[1]*SCALE: yright = self.buildarea[1]*SCALE for x in range(0, self.buildarea[0], 10): if x%50 == 0: c = ltGrey else: c = dkGrey x = (x - self.offsetx)*self.zoom*SCALE if x >= 0 and x <= self.buildarea[0]*SCALE: self.canvas.create_line(x, yleft, x, yright, fill=c, tags="GRID") xtop = (0 - self.offsetx)*self.zoom*SCALE if xtop <0: xtop = 0 xbottom = (self.buildarea[0] - self.offsetx)*self.zoom*SCALE if xbottom > self.buildarea[0]*SCALE: xbottom = self.buildarea[0]*SCALE for y in range(0, self.buildarea[1], 10): if y%50 == 0: c = dkGrey else: c = ltGrey y = (y - self.offsety)*self.zoom*SCALE if y >= 0 and y <= self.buildarea[1]*SCALE: self.canvas.create_line(xtop, y, xbottom, y, fill=c, tags="GRID") def drawLayer(self, layername): if layername == self.currentdrawn: #print "deleting object" #self.canvas.delete("OBJECT") self.drawOneLayer(layername, updateonly=True) else: self.canvas.delete("OBJECT") self.canvas.delete("SHADOW") pl = self.model.prevLayer(layername) if pl and self.settings.showprevious: self.drawOneLayer(pl, background=True) self.drawOneLayer(layername) self.currentdrawn = layername def drawOneLayer(self, layername, background=False, updateonly=False): if not self.model.setLayer(layername): return lx = self.model.getLayerNumber(layername) prev = [None, None] segmentextrusion = 0.0 cx = 0 segments = 0 if background: tag = "SHADOW" else: tag = "OBJECT" if not background and not updateonly: self.label.config(text="file: %.30s z = %.3f (%d/%d)" % (os.path.basename(self.filename), self.model.getLayerHeight(layername), lx+1, self.model.countLayers())) for p in self.model: if prev == [None, None]: prev = [p[0], p[1]] if segments != 0: segments = 0 cx = (cx + 1) % len(colors) else: if p[3] <= segmentextrusion or p[3] == -1: if p[3] == -1: segmentextrusion = 0.0 if not updateonly: if not background and self.settings.showmoves: c = "white" if prev != [p[0], p[1]]: (x1, y1) = self.transform(prev[0], self.buildarea[1]-prev[1]) (x2, y2) = self.transform(p[0], self.buildarea[1]-p[1]) self.canvas.create_line(x1, y1, x2, y2, fill=c, tags=tag) if segments != 0: segments = 0 cx = (cx + 1) % len(colors) else: if prev != [p[0], p[1]]: segments += 1 segmentextrusion = p[3] if background: c = grey f = not updateonly elif self.printprogress >= p[5]: c = "red" f = True else: c = colors[cx] f = not updateonly if f: (x1, y1) = self.transform(prev[0], self.buildarea[1]-prev[1]) (x2, y2) = self.transform(p[0], self.buildarea[1]-p[1]) self.canvas.create_line(x1, y1, x2, y2, fill=c, tags=tag) prev = [p[0], p[1]] def transform(self, ptx, pty): x = (ptx - self.offsetx)*self.zoom*SCALE y = (pty - self.offsety)*self.zoom*SCALE return (x, y)
class PypeTkPad(object): def __init__(self, master, queue, pypeOutput): self.queue = queue self.pypeOutput = pypeOutput self.master = master self.master.title('PypePad') self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0)) self.master.minsize(300, 100) self.output_file_name = None self.BuildMainFrame() self.UpdateOutput() def NewCommand(self): self.ClearAllCommand() def OpenCommand(self): import tkFileDialog from Tkinter import END openfile = tkFileDialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END, line) def SaveCommand(self): import tkFileDialog from Tkinter import END saveasfile = tkFileDialog.asksaveasfile() if not saveasfile: return alltext = self.text_input.get("1.0", END) saveasfile.write(alltext) def QuitCommand(self): self.master.quit() def ClearInputCommand(self): from Tkinter import END self.text_input.delete("1.0", END) def ClearOutputCommand(self): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.delete("1.0", END) self.text_output["state"] = DISABLED self.text_output.see(END) self.text_output.update() def ClearAllCommand(self): self.ClearInputCommand() self.ClearOutputCommand() def OutputFileCommand(self): import tkFileDialog outputfilename = tkFileDialog.asksaveasfilename() if sys.platform == 'win32' and len(outputfilename.split()) > 1: outputfilename = '"%s"' % outputfilename self.output_file_name = outputfilename def AboutCommand(self): self.OutputText('\n') self.OutputText( '* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n') self.OutputText('\n') def UpdateOutput(self): if self.pypeOutput: text = self.pypeOutput.pop(0) self.output_stream.write(text) self.master.after(10, self.UpdateOutput) def RunPype(self, arguments): if not arguments: return if self.output_to_file.get() is not 'n' and self.output_file_name: self.output_stream.output_to_file = True self.output_stream.output_file = open(self.output_file_name, self.output_to_file.get()) else: self.output_stream.output_to_file = False self.queue.append(arguments) def GetWordUnderCursor(self): from Tkinter import CURRENT splitindex = self.text_input.index(CURRENT).split('.') line = self.text_input.get(splitindex[0] + ".0", splitindex[0] + ".end") wordstart = line.rfind(' ', 0, int(splitindex[1]) - 1) + 1 wordend = line.find(' ', int(splitindex[1])) if wordend == -1: wordend = len(line) word = line[wordstart:wordend] return word def GetWordIndex(self): startindex = self.text_input.index("insert-1c wordstart") endindex = self.text_input.index("insert-1c wordend") if self.text_input.get(startindex + '-1c') == '-' and self.text_input.get( startindex + '-2c') == '-': startindex = self.text_input.index("insert-1c wordstart -2c") elif self.text_input.get(startindex + '-1c') == '-' and self.text_input.get( startindex + '-2c') == ' ': startindex = self.text_input.index("insert-1c wordstart -1c") self.wordIndex[0] = startindex self.wordIndex[1] = endindex word = self.text_input.get(self.wordIndex[0], self.wordIndex[1]) return word def GetLogicalLine(self, physicallineid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallineid]] def GetLogicalLineRange(self, physicallinefirstid, physicallinelastid): indexes, lines = self.GetLogicalLines() return lines[indexes[physicallinefirstid]:indexes[physicallinelastid] + 1] def GetAllLogicalLines(self): return self.GetLogicalLines()[1] def GetLogicalLines(self): from Tkinter import END physicallines = self.text_input.get("1.0", END).split('\n') lines = [] indexes = [0] * len(physicallines) lineid = 0 previousline = "" join = 0 for line in physicallines: if line.startswith('#'): if join: indexes[lineid] = indexes[lineid - 1] elif join: if line.endswith('\\'): lines[-1] = lines[-1] + " " + line[:-1] join = 1 else: lines[-1] = lines[-1] + " " + line join = 0 indexes[lineid] = indexes[lineid - 1] else: if line.endswith('\\'): join = 1 lines.append(line[:-1]) else: lines.append(line) join = 0 if lineid > 0: indexes[lineid] = indexes[lineid - 1] + 1 lineid += 1 return indexes, lines def GetLineUnderCursor(self): from Tkinter import INSERT currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1 return self.GetLogicalLine(currentlineid) def RunAllCommand(self): lines = self.GetAllLogicalLines() for line in lines: if line and line.strip(): self.RunPype(line) def RunLineCommand(self): line = self.GetLineUnderCursor() if line and line.strip(): self.RunPype(line) def RunSelectionCommand(self): from Tkinter import TclError, SEL_FIRST, SEL_LAST try: firstlineid = int( self.text_input.index(SEL_FIRST).split('.')[0]) - 1 lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1 lines = self.GetLogicalLineRange(firstlineid, lastlineid) for line in lines: self.RunPype(line) except TclError: pass def GetSuggestionsList(self, word): list = [] try: exec('import vmtkscripts') except ImportError: return None if word.startswith('--'): list = ['--pipe', '--help'] elif word.startswith('-'): optionlist = [] scriptindex = self.text_input.search('vmtk', self.wordIndex[0], backwards=1) moduleName = self.text_input.get(scriptindex, scriptindex + ' wordend') try: exec('import ' + moduleName) exec('scriptObjectClassName = ' + moduleName + '.' + moduleName) exec('scriptObject = ' + moduleName + '.' + scriptObjectClassName + '()') members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-' + member.OptionName) exec( 'list = [option for option in optionlist if option.count(word)]' ) except: return list else: exec( 'list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ]' ) return list def FillSuggestionsList(self, word): from Tkinter import END self.suggestionslist.delete(0, END) suggestions = self.GetSuggestionsList(word) for suggestion in suggestions: self.suggestionslist.insert(END, suggestion) def ReplaceTextCommand(self, word): self.text_input.delete(self.wordIndex[0], self.wordIndex[1]) self.text_input.insert(self.wordIndex[0], word) self.text_input.focus_set() def ShowHelpCommand(self): word = self.GetWordUnderCursor() self.OutputText(word) if word: self.RunPype(word + ' --help') else: self.OutputText('Enter your vmtk Pype above and Run.\n') def AutoCompleteCommand(self): word = self.GetWordIndex() self.suggestionswindow.withdraw() if word: self.FillSuggestionsList(word) self.suggestionswindow.geometry( "%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(), self.text_output.winfo_rooty())) self.suggestionswindow.deiconify() self.suggestionswindow.lift() def InsertScriptName(self, scriptname): from Tkinter import INSERT self.text_input.insert(INSERT, scriptname + ' ') def InsertFileName(self): from Tkinter import INSERT import tkFileDialog openfilename = tkFileDialog.askopenfilename() if not openfilename: return if len(openfilename.split()) > 1: openfilename = '"%s"' % openfilename self.text_input.insert(INSERT, openfilename + ' ') def KeyPressHandler(self, event): if event.keysym == "Tab": self.AutoCompleteCommand() self.suggestionslist.focus_set() self.suggestionslist.selection_set(0) return "break" else: self.text_input.focus_set() def TopKeyPressHandler(self, event): from Tkinter import ACTIVE, INSERT if event.keysym in ['Down', 'Up']: self.suggestionslist.focus_set() elif event.keysym == "Return": word = self.suggestionslist.get(ACTIVE) self.ReplaceTextCommand(word) self.suggestionswindow.withdraw() self.text_input.focus_set() elif len(event.keysym) == 1: self.suggestionswindow.withdraw() self.text_input.insert(INSERT, event.keysym) self.text_input.focus_set() else: self.suggestionswindow.withdraw() self.text_input.focus_set() def NewHandler(self, event): self.NewCommand() def OpenHandler(self, event): self.OpenCommand() def SaveHandler(self, event): self.SaveCommand() def InsertFileNameHandler(self, event): self.InsertFileName() return "break" def QuitHandler(self, event): self.QuitCommand() def ShowHelpHandler(self, event): self.ShowHelpCommand() def RunKeyboardHandler(self, event): from Tkinter import SEL_FIRST, TclError try: self.text_input.index(SEL_FIRST) self.RunSelectionCommand() except TclError: self.RunLineCommand() return "break" def RunAllHandler(self, event): self.RunAllCommand() def PopupHandler(self, event): try: self.popupmenu.tk_popup(event.x_root, event.y_root, 0) finally: self.popupmenu.grab_release() def OutputText(self, text): from Tkinter import NORMAL, END, DISABLED self.text_output["state"] = NORMAL self.text_output.insert(END, text) self.text_output["state"] = DISABLED def BuildScriptMenu(self, parentmenu, modulename): from Tkinter import Menu menu = Menu(parentmenu, bd=1, activeborderwidth=0) try: exec('import ' + modulename) except ImportError: return None scriptnames = [] exec('scriptnames = [scriptname for scriptname in ' + modulename + '.__all__]') menulength = 20 for i in range(len(scriptnames) / menulength + 1): subscriptnames = scriptnames[i * menulength:(i + 1) * menulength] if not subscriptnames: break submenu = Menu(menu, bd=1, activeborderwidth=0) menu.add_cascade(label=subscriptnames[0] + "...", menu=submenu) for scriptname in subscriptnames: callback = CallbackShim(self.InsertScriptName, scriptname) submenu.add_command(label=scriptname, command=callback) return menu def BuildMainFrame(self): from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED menu = Menu(self.master, activeborderwidth=0, bd=0) self.master.config(menu=menu) filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0) menu.add_cascade(label="File", underline=0, menu=filemenu) filemenu.add_command(label="New", accelerator='Ctrl+N', command=self.NewCommand) filemenu.add_command(label="Open...", accelerator='Ctrl+O', command=self.OpenCommand) filemenu.add_command(label="Save as...", accelerator='Ctrl+S', command=self.SaveCommand) filemenu.add_separator() filemenu.add_command(label="Quit", accelerator='Ctrl+Q', command=self.QuitCommand) self.log_on = IntVar() self.log_on.set(1) self.output_to_file = StringVar() self.output_to_file.set('n') scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0) modulenames = ['vmtkscripts'] for modulename in modulenames: scriptsubmenu = self.BuildScriptMenu(menu, modulename) if scriptsubmenu: scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu) editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0) menu.add_cascade(label="Edit", underline=0, menu=editmenu) editmenu.add_cascade(label="Insert script", menu=scriptmenu) editmenu.add_command(label="Insert file name", accelerator='Ctrl+F', command=self.InsertFileName) editmenu.add_separator() editmenu.add_command(label="Clear input", command=self.ClearInputCommand) editmenu.add_command(label="Clear output", command=self.ClearOutputCommand) editmenu.add_command(label="Clear all", command=self.ClearAllCommand) editmenu.add_separator() editmenu.add_checkbutton(label="Log", variable=self.log_on) editmenu.add_separator() editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file, value='n') editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file, value='w') editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file, value='a') editmenu.add_command(label="Output file...", command=self.OutputFileCommand) runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0) menu.add_cascade(label="Run", underline=0, menu=runmenu) runmenu.add_command(label="Run all", command=self.RunAllCommand) runmenu.add_command(label="Run current line", command=self.RunLineCommand) runmenu.add_command(label="Run selection", command=self.RunSelectionCommand) helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0) menu.add_cascade(label="Help", underline=0, menu=helpmenu) helpmenu.add_command(label="Help", underline=0, accelerator='F1', command=self.ShowHelpCommand) helpmenu.add_command(label="About", underline=0, command=self.AboutCommand) self.master.bind("<Control-KeyPress-q>", self.QuitHandler) self.master.bind("<Control-KeyPress-n>", self.NewHandler) self.master.bind("<Control-KeyPress-o>", self.OpenHandler) self.master.bind("<Control-KeyPress-s>", self.SaveHandler) self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler) self.master.bind("<KeyPress-F1>", self.ShowHelpHandler) self.master.bind("<KeyPress>", self.KeyPressHandler) self.wordIndex = ['1.0', '1.0'] self.suggestionswindow = Toplevel(bg='#ffffff', bd=0, height=50, width=600, highlightthickness=0, takefocus=True) self.suggestionswindow.overrideredirect(1) self.suggestionslist = Listbox(self.suggestionswindow, bg='#ffffff', bd=1, fg='#336699', activestyle='none', highlightthickness=0, height=9) self.suggestionslist.insert(END, "foo") self.suggestionslist.pack(side=TOP, fill=X) self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler) self.suggestionswindow.withdraw() self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) content = Frame(self.master, bd=0, padx=2, pady=2) content.grid(row=0, column=0, sticky=N + S + W + E) content.rowconfigure(0, weight=1, minsize=50) content.rowconfigure(1, weight=0) content.columnconfigure(0, weight=1) panes = PanedWindow(content, orient=VERTICAL, bd=1, sashwidth=8, sashpad=0, sashrelief=RAISED, showhandle=True) panes.grid(row=0, column=0, sticky=N + S + W + E) frame1 = Frame(panes, bd=0) frame1.grid(row=0, column=0, sticky=N + S + W + E) frame1.columnconfigure(0, weight=1) frame1.columnconfigure(1, weight=0) frame1.rowconfigure(0, weight=1) panes.add(frame1, height=300, minsize=20) frame2 = Frame(panes, bd=0) frame2.grid(row=1, column=0, sticky=N + S + W + E) frame2.columnconfigure(0, weight=1) frame2.columnconfigure(1, weight=0) frame2.rowconfigure(0, weight=1) panes.add(frame2, minsize=20) self.text_input = Text(frame1, bg='#ffffff', bd=1, highlightthickness=0) self.text_input.bind("<KeyPress>", self.KeyPressHandler) self.text_input.bind("<Button-3>", self.PopupHandler) self.text_input.bind("<Control-Return>", self.RunKeyboardHandler) self.input_scrollbar = Scrollbar(frame1, orient=VERTICAL, command=self.text_input.yview) self.text_input["yscrollcommand"] = self.input_scrollbar.set self.text_output = Text(frame2, state=DISABLED, bd=1, bg='#ffffff', highlightthickness=0) self.output_scrollbar = Scrollbar(frame2, orient=VERTICAL, command=self.text_output.yview) self.text_output["yscrollcommand"] = self.output_scrollbar.set self.text_entry = Entry(content, bd=1, bg='#ffffff', state=DISABLED, highlightthickness=0) self.text_input.focus_set() self.text_input.grid(row=0, column=0, sticky=N + S + W + E) self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E) self.text_output.grid(row=0, column=0, sticky=N + S + W + E) self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E) self.text_entry.grid(row=1, column=0, sticky=N + S + W + E) self.popupmenu = Menu(self.text_input, tearoff=1, bd=0) self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand) self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu) self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName) self.popupmenu.add_separator() self.popupmenu.add_command(label="Run all", command=self.RunAllCommand) self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand) self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand) self.output_stream = TkPadOutputStream(self.text_output) self.input_stream = TkPadInputStream(self.text_entry, self.output_stream)
def CreateListBox(parent, x, y, val): """ Listbox to show the spelling list """ lstbox = Listbox(parent, listvariable=val, selectmode="extended") lstbox.grid(column=x, row=y) sbar = Scrollbar(parent, orient="vertical", command=lstbox.yview) sbar.grid(column=x+1, row=y, sticky="ns") lstbox['yscrollcommand'] = sbar.set return lstbox
class ResultList(Frame): """ Result List widget """ def __init__(self, master=None): Frame.__init__(self, master, padx=3, pady=3) self.columnconfigure(0, weight=1, minsize=50) self.columnconfigure(1, weight=1000) self.columnconfigure(2, weight=1, minsize=10) self.__createWidgets() self.show() def __createWidgets(self): self.lbl = Label(text="") self.lbl.grid(row=1, column=0, columnspan=2, in_=self) self.__hide_button = Button(text="Hide", command=self.hide) self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self) self.__yScroll = Scrollbar(orient=VERTICAL) self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE) self.__yScroll.config(command=self.list.yview) def show(self): self.__hide_button.config(text="Hide", command=self.hide) self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self) self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self) def hide(self): self.__hide_button.config(text="Show", command=self.show) self.list.grid_forget() self.__yScroll.grid_forget() def clear(self): self.list.delete(0, END) def fill(self, valList): self.clear() for v in valList: self.list.insert(END, v) self.list.see(0) self.select(0) def append(self, val): self.list.insert(END, val) self.list.see(END) def select(self, index=0): self.list.selection_set(index) def selected(self): return int(self.list.curselection()[0]) def width(self, width): self.list.config(width=width)
class Viewer(Frame): def __init__(self, master,x=600,y=200, onLeft=None, onRight=None, **kwargs): self.root=master self.xsize=x self.ysize=y self.onLeft=onLeft self.onRight=onRight self.ratio=100. Frame.__init__(self, master,width=x,height=y, **kwargs) self.canvas = Canvas(self, width=x, height=y, background="white") self.xsb = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.ysb = Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set) self.canvas.configure(scrollregion=(0,0,x,y)) self.xsb.grid(row=1, column=0, sticky="ew") self.ysb.grid(row=0, column=1, sticky="ns") self.canvas.grid(row=0, column=0, sticky="nsew") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.canvas.bind("<Button-1>", self.clickL) self.canvas.bind("<Button-3>", self.clickR) # This is what enables using the mouse: self.canvas.bind("<ButtonPress-1>", self.move_start) self.canvas.bind("<B1-Motion>", self.move_move) #linux scroll self.canvas.bind("<Button-4>", self.zoomerP) self.canvas.bind("<Button-5>", self.zoomerM) self.canvas.bind_all("<Prior>", self.zoomerP) self.canvas.bind_all("<Next>", self.zoomerM) self.canvas.bind_all("E", self.zoomExtens) #windows scroll self.canvas.bind_all("<MouseWheel>",self.zoomer) def reset(self): pass def set_title(self, title): self.root.title( title) #move def move_start(self, event): self.canvas.scan_mark(event.x, event.y) return True def move_move(self, event): self.canvas.scan_dragto(event.x, event.y, gain=1) return True #windows zoom def zoomer(self,event): if (event.delta > 0): self.ratio *= 1.1 elif (event.delta < 0): self.ratio *= 0.9 self.redraw() def redraw(self): self.canvas.delete("all") self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomExtens(self, *args): x0,y0,x1,y1 = self.canvas.bbox("all") xlen=x1-x0 ylen=y1-y0 height=self.canvas.winfo_height() width=self.canvas.winfo_width() unfit=min(width/float(xlen), height/float(ylen)) self.ratio*=unfit self.redraw() # """" if xlen and ylen: self ratio*= self.canvas.scale("all", xlen/2., ylen/2., float(self.xsize)/xlen, float(self.ysize)/ylen) self.canvas.configure(scrollregion = self.canvas.bbox("all")) """ #linux zoom def zoomerP(self,event): self.canvas.scale("all", event.x, event.y, 1.1, 1.1) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomerM(self,event): self.canvas.scale("all", event.x, event.y, 0.9, 0.9) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def pose2p(self, pose): x,y=pose[:2] return int(x*self.ratio), -int(y*self.ratio) def line2p(self, line): if type(line[0]) in (float, int): line=zip(line[::2],line[1::2]) return map(self.pose2p, line) def p2m(self, x, y): return x/self.ratio, -y/self.ratio def create_line(self, coords, **kwargs): return self.canvas.create_line(self.line2p(coords), **kwargs) def create_polygon(self, coords, **kwargs): return self.canvas.create_polygon(self.line2p(coords), **kwargs) def delete(self, object): self.canvas.delete(object) def clickL(self, event): if self.onLeft: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onLeft(x,y) return True def clickR(self, event): if self.onRight: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onRight(x,y) return True