class ShapesMenu(object): """ """ def __init__(self, master, line_collection): try: self.width_of_entry = len(line_collection[0]) except IndexError: self.width_of_entry = 0 self.top = Toplevel(master) self.current_lines_listbox = Listbox(self.top) self.removed_lines_listbox = Listbox(self.top) self.submit = Button(self.top, text = "Ok", command=self.submit) self.remove_button = Button(self.top, text = "Remove", command=self.remove_line) self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy) self.top.bind("<Return>", func=self.submit) self.current_lines = line_collection self.removed_lines = [] self.ids_internal = [] self.ids = [] for index, line in enumerate(self.current_lines): #removes the point data and converts the rest to strings id = line[1] if id not in self.ids_internal: self.ids_internal.append(id) self.ids.append(id) line = [str(element) for element in line[1:]] #put into the list self.current_lines_listbox.insert(index, " ".join(line)) self.current_lines_listbox.grid(row=0, column=0, columnspan=3) self.submit.grid(row=1, column=1) self.cancel.grid(row=1, column=2) self.remove_button.grid(row=1, column=0) def submit(self): #expose the internal IDs to remove to the exterior methods self.ids = self.ids_internal self.top.destroy() def remove_line(self): """Take the active line and remove it""" line_to_remove = self.current_lines_listbox.get(ANCHOR) id_to_remove = int(line_to_remove.split(" ")[0]) #remove it from the ID list self.ids_internal.remove(id_to_remove) #remove it from the listbox self.current_lines_listbox = self.current_lines_listbox.delete(ANCHOR)
class ZoomWindow(object): """description of class""" def __init__(self, master): self.top = Toplevel(master) self.entry_width = 15 self.set_none_limits() self.real_max_label = Label(self.top, text="Real Max: ") self.real_min_label = Label(self.top, text="Real Min: ") self.imag_max_label = Label(self.top, text="Imag Max: ") self.imag_min_label = Label(self.top, text="Imag Min: ") self.real_max_entry = Entry(self.top, width=self.entry_width) self.real_min_entry = Entry(self.top, width=self.entry_width) self.imag_max_entry = Entry(self.top, width=self.entry_width) self.imag_min_entry = Entry(self.top, width=self.entry_width) self.submit_button = Button(self.top, text="Submit", command=self.submit) self.cancel_button = Button(self.top, text="Cancel", command=self.top.destroy) self.real_max_label.grid(row=0, column=0) self.real_min_label.grid(row=1, column=0) self.imag_max_label.grid(row=2, column=0) self.imag_min_label.grid(row=3, column=0) self.real_max_entry.grid(row=0, column=1) self.real_min_entry.grid(row=1, column=1) self.imag_max_entry.grid(row=2, column=1) self.imag_min_entry.grid(row=3, column=1) self.submit_button.grid(row=4, column=0) self.cancel_button.grid(row=4, column=1) self.top.bind("<Return>", self.submit) self.top.bind("<Escape>", self.top.destroy) self.real_max_entry.focus() def set_none_limits(self): self.imag_min, self.imag_max, self.real_max, self.real_min = (None, None, None, None) def submit(self, event=None): try: self.imag_min = float(self.imag_min_entry.get()) self.imag_max = float(self.imag_max_entry.get()) self.real_min = float(self.real_min_entry.get()) self.real_max = float(self.real_max_entry.get()) if self.imag_min > self.imag_max or self.real_min > self.real_max: self.set_none_limits() print("A min field exceeds a max field") except TypeError: print("Values passed are not real numbers") self.top.destroy()
def new_random_swiss(main): players = [] def add_player(event): if e.get() is "": return players.append(e.get()) Lb.delete(0,END) for x in players: Lb.insert(0,x) e.delete(0,END) def remove_player(): l=len(players)-1 if Lb.curselection(): for x in Lb.curselection(): Lb.delete(x) players.pop(l-x) else: Lb.delete(0) players.pop(-1) Lb.delete(0,END) for x in players: Lb.insert(0,x) top = Toplevel(main) top.title("New Random Swiss") top.bind("<Return>",add_player) center_size(top,360,180) Label(top, text='Name:').grid(row=0,column=0) e = Entry(top,width=12) e.grid(row=0,column=1) e.focus_force() Button(top,text='Add', command=lambda:add_player(None) ).grid(row=1,column=0) Button(top,text='Remove', command=remove_player ).grid(row=1,column=1) Button(top,text='Cancel', command=top.destroy ).grid(row=2,column=0) Button(top,text='Finish', command=lambda:create_single_swiss(players,main)).grid(row=2,column=1) Sb = Scrollbar(top) Sb.grid(row=0,column=3,rowspan=3) Lb = Listbox(top,selectmode=EXTENDED,yscrollcommand=Sb.set) Lb.grid(row=0,rowspan=3,column=2) Sb.config(command=Lb.yview)
def show_about(self): about = Toplevel(self.master) about.title('About {}'.format(self.version[:-5])) about.focus() about.resizable(0, 0) logo_lbl = Label(about, image=self.logo) logo_lbl.image = self.logo logo_lbl.grid(row=0, column=0, padx='7 11', pady=13, sticky='n') about_frame = Frame(about, padding='0 10 10 10') about_frame.grid(row=0, column=1) Label(about_frame, text=self.version).grid(sticky='w') Label(about_frame, text='Developer: Joel W. Dafoe').grid(pady='6', sticky='w') link = Link(about_frame, text='http://cyberdatx.com', foreground='blue', cursor='hand2') link.grid(sticky='w') link.bind('<Button-1>', lambda e: webbrowser.open('http://cyberdatx.com')) Label(about_frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky='w') cls_btn = Button(about_frame, text='OK', command=about.destroy) cls_btn.grid(column=1, sticky='e') cls_btn.focus() about.bind('<Return>', lambda e: cls_btn.invoke())
def create_widgets(self): '''Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row. ''' top = Toplevel(self.root) top.bind("<Return>", self.default_command) top.bind("<Escape>", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) top.wm_iconname(self.icon) self.top = top self.row = 0 self.top.grid_columnconfigure(0, pad=2, weight=0) self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100) self.create_entries() # row 0 (and maybe 1), cols 0, 1 self.create_option_buttons() # next row, cols 0, 1 self.create_other_buttons() # next row, cols 0, 1 self.create_command_buttons() # col 2, all rows
def nameHandler(name, message): '''Takes a string name and character, provides an interface for correcting the illegal name, returns a new legal string name.''' #todo: create a proper validate method def destroy(*args): root.destroy() root = Toplevel() root.title('Bad Name') root.resizable(False, False) root.after(100, root.focus_force) #todo: temp? mainFrame = ttk.Frame(root, padding=MAIN_PAD) mainFrame.grid(column=0, row=0, sticky='nwes') newname = StringVar(value=name) nameEntry = ttk.Entry(mainFrame, textvariable=newname) nameEntry.grid(row=1, sticky='we') ttk.Label(mainFrame, text=message).grid(row=0) for child in mainFrame.winfo_children(): child.grid(padx=5, pady=5) nameEntry.after(100, nameEntry.focus) #todo: temp? root.bind('<Return>', destroy) root.wait_window() #todo: disable the ability to close the window instead? add abort option? if len(newname.get()) < 1: return nameHandler(name, message) else: return newname.get()
def do(): r, c = self.get_cursor_pos('insert') script = jedi.api.Interpreter( self.text.get(f'{r}.4', 'end-1c'), [Scripting.namespaces['locals'], Scripting.namespaces['globals']]) if len(script.completions())==0: return 'break' if len(script.completions())==1: cstr = script.completions()[0].complete self.text.insert('end', cstr) return 'break' acw = Toplevel(self.text) acw.wm_overrideredirect(1) acw.wm_attributes('-topmost', True) seltext = Label(acw, anchor='w', justify='left') seltext.pack(expand='yes', fill='x') namelist = ScrolledList(acw) namelist.pack(expand='yes', fill='both') namelist.list_config(selectmode='single') x, y, w, h = self.text.bbox('insert') x += self.text.winfo_rootx() y += self.text.winfo_rooty() # y+h is the position below the current line. acw.geometry(f'+{x}+{y}') namelist.list.focus_set() def on_exit(event): acw.destroy() acw.bind('<FocusOut>', on_exit) namelist.list.bind('<Escape>', on_exit) def on_updown(event, direction): cursel = int(namelist.current_selection[0]) newsel = cursel + direction if not (0<= newsel < namelist.length): return 'break' namelist.selection_clear(cursel) namelist.selection_set(newsel) namelist.see(newsel) return 'break' namelist.list.bind('<Down>', lambda event:on_updown(event, 1)) namelist.list.bind('<Tab>', lambda event:on_updown(event, 1)) namelist.list.bind('<Up>', lambda event:on_updown(event, -1)) namelist.list.bind('<Shift-Tab>', lambda event:on_updown(event, -1)) for completion in script.completions(): namelist.append(completion.name) # init namelist.selection_set(0) def on_select(event): cursel = int(namelist.current_selection[0]) cstr = script.completions()[cursel].complete self.text.insert('end', cstr) on_exit(None) namelist.list.bind('<Return>', on_select) namelist.list.bind('<ButtonRelease-1>', on_select) keyseq = [''] def on_key_press(event): if (event.keysym not in self.root_node.lang_center.wavesynscript.constants.KEYSYM_MODIFIERS.value) and \ (event.keysym not in self.root_node.lang_center.wavesynscript.constants.KEYSYM_CURSORKEYS.value): if event.keysym=='BackSpace': keyseq[0] = keyseq[0][:-1] else: keyseq[0] += event.keysym seltext['text'] = keyseq[0] for idx, completion in enumerate(script.completions()): if completion.complete.startswith(keyseq[0]): cursel = int(namelist.current_selection[0]) namelist.selection_clear(cursel) namelist.selection_set(idx) namelist.see(idx) return on_exit(None) else: return namelist.list.bind('<KeyPress>', on_key_press)
class GUI(): __server = transmission() __isOn = False __name = "Anonymous" def autoScroll(self): self.__isOn = False if self.__isOn else True def pullName(self, event = None): self.__name = str(self.name.get()) self.name.delete( first = 0, last = len(self.name.get()) ) self.window.destroy() def nameInput(self): self.window = Toplevel(self.root) self.name = Entry( self.window, ) self.nameLabel = Label( self.window, text = "Name", padx = 10, pady = 10 ) self.name.focus_set() self.nameLabel.pack(side = "top") self.name.pack(side = "bottom") self.window.bind('<Return>', self.pullName) #window.destroy() def reFresh(self): print("in") #self.showChat.delete('1.0', END) self.showChat.config(state = 'normal') self.showChat.insert(END, self.__server.readingLog()) self.showChat.config(state = 'disabled') if self.__isOn: self.showChat.see('end') self.root.after(1000, self.reFresh) def sendMessage(self, event=None): self.__server.writingLog(self.userInput.get(), self.__name) self.userInput.delete(first = 0, last=len(self.userInput.get())) def __init__(self): self.root = Tk() self.nameInput() self.menuBar = Menu( self.root, activebackground = "orange2", bg = "orange2", tearoff = 0 ) self.showChat = ScrolledText( self.root, width=30, height = 15, state = 'normal') self.userInput = Entry(self.root) self.sendButton = Button( self.root, text = "Send", command = lambda: self.sendMessage(), background = "orange2" ) self.userInput.focus_set() self.showChat.grid( row = 1, column = 1, columnspan = 7, pady = 5, padx = 10 ) self.userInput.grid( row = 2, column = 1, columnspan = 2, pady = 10, padx = 10 ) self.sendButton.grid( row = 2, column = 7, pady = 10, padx = 10 ) #self.root.geometry("800x800") #https://www.tutorialspoint.com/python3/tk_menu.htm #self.menuBar.config(width = 3) self.root.config(menu=self.menuBar) self.options = Menu( self.menuBar, tearoff = 0) self.menuBar.add_cascade( label='Options', menu = self.options) #options.add_command(label = 'Scroll-Lock') self.options.add_checkbutton( label = 'Auto-Scroll', command = self.autoScroll, background = "grey", activebackground = "grey", selectcolor = "white", onvalue=True, offvalue=False, variable = self.__isOn ) self.options.add_command( label = 'Name', command = self.nameInput, background = "grey", #activebackground = "grey", #selectcolor = "white", ) self.root.after(1000, self.reFresh) self.root.title('Erik Tyryshkin Chat Program') self.root.configure(bg='grey') self.root.bind('<Return>', self.sendMessage) self.root.mainloop()
def jedi_autocomplete(self, *args): # print('testing') code = self.tab.text.get('1.0', "end") line_column = self.tab.text.index('insert').split('.') line, column = int(line_column[0]), int(line_column[1]) # print(line, column) if self.tab.filename: # script = jedi.Script(code=code,path=self.tab.filename) # completion = script.complete(line=line,column=column) # # print(completion) # else: script = jedi.Script(code=code) completion = script.complete(line=line, column=column) completions = [] for i, names in enumerate(completion): completions.append(completion[i].name) # print(completion) # https://github.com/python/cpython/blob/master/Lib/idlelib/autocomplete_w.py if completions: text = self.tab.text text.see(text.index('insert')) x, y, cx, cy = text.bbox(text.index('insert')) acw = Toplevel(master) def key(event): # print("pressed", repr(event.char)) key_pressed = repr(event.char) if not completions: print('notnone') if key_pressed == "'\\r'": autocomplete_selection = entry.get() first_char = text.index("insert -1c wordstart") last_char = text.index('insert -1c wordend') self.tab.text.delete(first_char, last_char) self.tab.text.insert(first_char, autocomplete_selection) acw.destroy() entry.destroy() # self.text.insert(text_index,autocomplete_selection) print(first_char, last_char, autocomplete_selection) def callback(event): entry.focus_set() print("clicked at", event.x, event.y) acw.bind("<Key>", key) # acw.bind("<Button-1>", callback) acw_width, acw_height = acw.winfo_width(), acw.winfo_height() text_width, text_height = text.winfo_width( ), text.winfo_height() new_x = text.winfo_rootx() + min( x, max(0, text_width - acw_width)) new_y = text.winfo_rooty() + y if (text_height - (y + cy) >= acw_height # enough height below or y < acw_height): # not enough height above # place acw below current line new_y += cy else: # place acw above current line new_y -= acw_height acw.wm_overrideredirect(True) acw.wm_geometry("+%d+%d" % (new_x, new_y)) from ttkwidgets.autocomplete import AutocompleteEntryListbox entry = AutocompleteEntryListbox(acw, width=20, completevalues=completions) entry.pack() return 'break'
class CFGEditor(object): """ A dialog window for creating and editing context free grammars. ``CFGEditor`` imposes the following restrictions: - All nonterminals must be strings consisting of word characters. - All terminals must be strings consisting of word characters and space characters. """ # Regular expressions used by _analyze_line. Precompile them, so # we can process the text faster. ARROW = SymbolWidget.SYMBOLS['rightarrow'] _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|(" + ARROW + "))") _ARROW_RE = re.compile("\s*(->|(" + ARROW + "))\s*") _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" + # LHS "(->|(" + ARROW + "))\s*" + # arrow r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$") # RHS _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|(" + ARROW + ")") _BOLD = ('helvetica', -12, 'bold') def __init__(self, parent, cfg=None, set_cfg_callback=None): self._parent = parent if cfg is not None: self._cfg = cfg else: self._cfg = ContextFreeGrammar(Nonterminal('S'), []) self._set_cfg_callback = set_cfg_callback self._highlight_matching_nonterminals = 1 # Create the top-level window. self._top = Toplevel(parent) self._init_bindings() self._init_startframe() self._startframe.pack(side='top', fill='x', expand=0) self._init_prodframe() self._prodframe.pack(side='top', fill='both', expand=1) self._init_buttons() self._buttonframe.pack(side='bottom', fill='x', expand=0) self._textwidget.focus() def _init_startframe(self): frame = self._startframe = Frame(self._top) self._start = Entry(frame) self._start.pack(side='right') Label(frame, text='Start Symbol:').pack(side='right') Label(frame, text='Productions:').pack(side='left') self._start.insert(0, self._cfg.start().symbol()) def _init_buttons(self): frame = self._buttonframe = Frame(self._top) Button(frame, text='Ok', command=self._ok, underline=0, takefocus=0).pack(side='left') Button(frame, text='Apply', command=self._apply, underline=0, takefocus=0).pack(side='left') Button( frame, text='Reset', command=self._reset, underline=0, takefocus=0, ).pack(side='left') Button(frame, text='Cancel', command=self._cancel, underline=0, takefocus=0).pack(side='left') Button(frame, text='Help', command=self._help, underline=0, takefocus=0).pack(side='right') def _init_bindings(self): self._top.title('CFG Editor') self._top.bind('<Control-q>', self._cancel) self._top.bind('<Alt-q>', self._cancel) self._top.bind('<Control-d>', self._cancel) #self._top.bind('<Control-x>', self._cancel) self._top.bind('<Alt-x>', self._cancel) self._top.bind('<Escape>', self._cancel) #self._top.bind('<Control-c>', self._cancel) self._top.bind('<Alt-c>', self._cancel) self._top.bind('<Control-o>', self._ok) self._top.bind('<Alt-o>', self._ok) self._top.bind('<Control-a>', self._apply) self._top.bind('<Alt-a>', self._apply) self._top.bind('<Control-r>', self._reset) self._top.bind('<Alt-r>', self._reset) self._top.bind('<Control-h>', self._help) self._top.bind('<Alt-h>', self._help) self._top.bind('<F1>', self._help) def _init_prodframe(self): self._prodframe = Frame(self._top) # Create the basic Text widget & scrollbar. self._textwidget = Text(self._prodframe, background='#e0e0e0', exportselection=1) self._textscroll = Scrollbar(self._prodframe, takefocus=0, orient='vertical') self._textwidget.config(yscrollcommand=self._textscroll.set) self._textscroll.config(command=self._textwidget.yview) self._textscroll.pack(side='right', fill='y') self._textwidget.pack(expand=1, fill='both', side='left') # Initialize the colorization tags. Each nonterminal gets its # own tag, so they aren't listed here. self._textwidget.tag_config('terminal', foreground='#006000') self._textwidget.tag_config('arrow', font='symbol') self._textwidget.tag_config('error', background='red') # Keep track of what line they're on. We use that to remember # to re-analyze a line whenever they leave it. self._linenum = 0 # Expand "->" to an arrow. self._top.bind('>', self._replace_arrows) # Re-colorize lines when appropriate. self._top.bind('<<Paste>>', self._analyze) self._top.bind('<KeyPress>', self._check_analyze) self._top.bind('<ButtonPress>', self._check_analyze) # Tab cycles focus. (why doesn't this work??) def cycle(e, textwidget=self._textwidget): textwidget.tk_focusNext().focus() self._textwidget.bind('<Tab>', cycle) prod_tuples = [(p.lhs(), [p.rhs()]) for p in self._cfg.productions()] for i in range(len(prod_tuples) - 1, 0, -1): if (prod_tuples[i][0] == prod_tuples[i - 1][0]): if () in prod_tuples[i][1]: continue if () in prod_tuples[i - 1][1]: continue print(prod_tuples[i - 1][1]) print(prod_tuples[i][1]) prod_tuples[i - 1][1].extend(prod_tuples[i][1]) del prod_tuples[i] for lhs, rhss in prod_tuples: print(lhs, rhss) s = '%s ->' % lhs for rhs in rhss: for elt in rhs: if isinstance(elt, Nonterminal): s += ' %s' % elt else: s += ' %r' % elt s += ' |' s = s[:-2] + '\n' self._textwidget.insert('end', s) self._analyze() # # Add the producitons to the text widget, and colorize them. # prod_by_lhs = {} # for prod in self._cfg.productions(): # if len(prod.rhs()) > 0: # prod_by_lhs.setdefault(prod.lhs(),[]).append(prod) # for (lhs, prods) in prod_by_lhs.items(): # self._textwidget.insert('end', '%s ->' % lhs) # self._textwidget.insert('end', self._rhs(prods[0])) # for prod in prods[1:]: # print '\t|'+self._rhs(prod), # self._textwidget.insert('end', '\t|'+self._rhs(prod)) # print # self._textwidget.insert('end', '\n') # for prod in self._cfg.productions(): # if len(prod.rhs()) == 0: # self._textwidget.insert('end', '%s' % prod) # self._analyze() # def _rhs(self, prod): # s = '' # for elt in prod.rhs(): # if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol() # else: s += ' %r' % elt # return s def _clear_tags(self, linenum): """ Remove all tags (except ``arrow`` and ``sel``) from the given line of the text widget used for editing the productions. """ start = '%d.0' % linenum end = '%d.end' % linenum for tag in self._textwidget.tag_names(): if tag not in ('arrow', 'sel'): self._textwidget.tag_remove(tag, start, end) def _check_analyze(self, *e): """ Check if we've moved to a new line. If we have, then remove all colorization from the line we moved to, and re-colorize the line that we moved from. """ linenum = int(self._textwidget.index('insert').split('.')[0]) if linenum != self._linenum: self._clear_tags(linenum) self._analyze_line(self._linenum) self._linenum = linenum def _replace_arrows(self, *e): """ Replace any ``'->'`` text strings with arrows (char \\256, in symbol font). This searches the whole buffer, but is fast enough to be done anytime they press '>'. """ arrow = '1.0' while True: arrow = self._textwidget.search('->', arrow, 'end+1char') if arrow == '': break self._textwidget.delete(arrow, arrow + '+2char') self._textwidget.insert(arrow, self.ARROW, 'arrow') self._textwidget.insert(arrow, '\t') arrow = '1.0' while True: arrow = self._textwidget.search(self.ARROW, arrow + '+1char', 'end+1char') if arrow == '': break self._textwidget.tag_add('arrow', arrow, arrow + '+1char') def _analyze_token(self, match, linenum): """ Given a line number and a regexp match for a token on that line, colorize the token. Note that the regexp match gives us the token's text, start index (on the line), and end index (on the line). """ # What type of token is it? if match.group()[0] in "'\"": tag = 'terminal' elif match.group() in ('->', self.ARROW): tag = 'arrow' else: # If it's a nonterminal, then set up new bindings, so we # can highlight all instances of that nonterminal when we # put the mouse over it. tag = 'nonterminal_' + match.group() if tag not in self._textwidget.tag_names(): self._init_nonterminal_tag(tag) start = '%d.%d' % (linenum, match.start()) end = '%d.%d' % (linenum, match.end()) self._textwidget.tag_add(tag, start, end) def _init_nonterminal_tag(self, tag, foreground='blue'): self._textwidget.tag_config(tag, foreground=foreground, font=CFGEditor._BOLD) if not self._highlight_matching_nonterminals: return def enter(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='#80ff80') def leave(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='') self._textwidget.tag_bind(tag, '<Enter>', enter) self._textwidget.tag_bind(tag, '<Leave>', leave) def _analyze_line(self, linenum): """ Colorize a given line. """ # Get rid of any tags that were previously on the line. self._clear_tags(linenum) # Get the line line's text string. line = self._textwidget.get( repr(linenum) + '.0', repr(linenum) + '.end') # If it's a valid production, then colorize each token. if CFGEditor._PRODUCTION_RE.match(line): # It's valid; Use _TOKEN_RE to tokenize the production, # and call analyze_token on each token. def analyze_token(match, self=self, linenum=linenum): self._analyze_token(match, linenum) return '' CFGEditor._TOKEN_RE.sub(analyze_token, line) elif line.strip() != '': # It's invalid; show the user where the error is. self._mark_error(linenum, line) def _mark_error(self, linenum, line): """ Mark the location of an error in a line. """ arrowmatch = CFGEditor._ARROW_RE.search(line) if not arrowmatch: # If there's no arrow at all, highlight the whole line. start = '%d.0' % linenum end = '%d.end' % linenum elif not CFGEditor._LHS_RE.match(line): # Otherwise, if the LHS is bad, highlight it. start = '%d.0' % linenum end = '%d.%d' % (linenum, arrowmatch.start()) else: # Otherwise, highlight the RHS. start = '%d.%d' % (linenum, arrowmatch.end()) end = '%d.end' % linenum # If we're highlighting 0 chars, highlight the whole line. if self._textwidget.compare(start, '==', end): start = '%d.0' % linenum end = '%d.end' % linenum self._textwidget.tag_add('error', start, end) def _analyze(self, *e): """ Replace ``->`` with arrows, and colorize the entire buffer. """ self._replace_arrows() numlines = int(self._textwidget.index('end').split('.')[0]) for linenum in range(1, numlines + 1): # line numbers start at 1. self._analyze_line(linenum) def _parse_productions(self): """ Parse the current contents of the textwidget buffer, to create a list of productions. """ productions = [] # Get the text, normalize it, and split it into lines. text = self._textwidget.get('1.0', 'end') text = re.sub(self.ARROW, '->', text) text = re.sub('\t', ' ', text) lines = text.split('\n') # Convert each line to a CFG production for line in lines: line = line.strip() if line == '': continue productions += parse_cfg_production(line) #if line.strip() == '': continue #if not CFGEditor._PRODUCTION_RE.match(line): # raise ValueError('Bad production string %r' % line) # #(lhs_str, rhs_str) = line.split('->') #lhs = Nonterminal(lhs_str.strip()) #rhs = [] #def parse_token(match, rhs=rhs): # token = match.group() # if token[0] in "'\"": rhs.append(token[1:-1]) # else: rhs.append(Nonterminal(token)) # return '' #CFGEditor._TOKEN_RE.sub(parse_token, rhs_str) # #productions.append(Production(lhs, *rhs)) return productions def _destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def _ok(self, *e): self._apply() self._destroy() def _apply(self, *e): productions = self._parse_productions() start = Nonterminal(self._start.get()) cfg = ContextFreeGrammar(start, productions) if self._set_cfg_callback is not None: self._set_cfg_callback(cfg) def _reset(self, *e): self._textwidget.delete('1.0', 'end') for production in self._cfg.productions(): self._textwidget.insert('end', '%s\n' % production) self._analyze() if self._set_cfg_callback is not None: self._set_cfg_callback(self._cfg) def _cancel(self, *e): try: self._reset() except: pass self._destroy() def _help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75, font='fixed') except: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75)
class Window_General_Function(tk.Tk): """ Cette classe permet d'initialiser la première fenêtre et contient les méthodes générales utilisées par les autres autres classes """ def __init__(self): """ self.container : une frame sur laquelle sont stockées les autres frames(différentes fenêtres). """ tk.Tk.__init__(self) self.list_team = [] self.list_frame = [] self.dict_key = {} self.container = tk.Frame(self) self.container.pack(side="top", fill="both", expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.geometry("600x600") self.color_font_entry = tkFont.Font(slant='italic') for F in (Menu_Create_Team, Window_Association_Buzzer, Window_Detect_Winner, Window_Show_Winner): self.list_frame.append(F) # je commence par invoquer la première fenêtre self.switch_frame(self.container, "Menu_Create_Team", controller=self) def switch_frame(self, container, window_name, controller): """ Fonction qui permet de changer de fênetre(frame) :param container: :param window_name: :param controller:représente une instance de classe que j'appellerai dans une autre classe dans le but d'hériter de certains attributs présents dans le __init__ d'une autre classe :return: """ for frame in self.list_frame: if window_name == frame.__name__: if window_name == "Window_Detect_Winner": liste_keys = [ i.get() for i in controller.list_variable_team.values() ] if len(liste_keys) != len(set(liste_keys)): return else: frame_to_call = frame(container, controller) frame_to_call.grid(row=0, column=0, sticky="nsew") frame_to_call.tkraise() elif window_name == "Window_Association_Buzzer": if len(self.dict_key) != len(self.list_team): pop_up_inegal_team_key = Toplevel(self) tk.Label( pop_up_inegal_team_key, text= "le nombre d'équipes choisies n'est pas égal au nombre de touches choisies" ).pack() elif len(self.list_team) <= 1: pop_up_team_number = Toplevel(self) tk.Label( pop_up_team_number, text="le nombre d'équipes choisies est insuffisant" ).pack() else: frame_to_call = frame(container, controller) frame_to_call.grid(row=0, column=0, sticky="nsew") frame_to_call.tkraise() else: frame_to_call = frame(container, controller) frame_to_call.grid(row=0, column=0, sticky="nsew") frame_to_call.tkraise() def add_equipe(self): """ Fonction qui permet d'ajouter des équipes à la liste des équipes(liste_equipe) avec le bouton "Ajouter équipe" :return: """ team = self.entree.get().strip() if len(list(team)) >= 1: if (team.lower() in self.list_team) is not True: self.list_team.append(team.lower()) self.entree.delete(0, END) def show_team(self): """ Fonction qui crée une nouvelle fenêtre avec la liste des différents équipes du jeu :return: """ list_team_showing = tk.Tk() for i in self.list_team: label = tk.Label(list_team_showing, text=i) label.pack() list_team_showing.mainloop() def add_key(self): self.dict_key = {} self.n = 0 self.add_key = Toplevel(self.Obj_Window_General_Function) self.add_key.focus_set() self.add_key.grab_set() self.add_key.geometry("700x100") tk.Label( self.add_key, text= "Appuie sur toutes les touches du clavier dont tu as besoin pour choisir lesquelles seront liées au buzzer." ).pack() self.text = StringVar() self.label_count = tk.Label(self.add_key, textvariable=self.text).pack() self.text.set("Vous avez actuellement ajouté 0 touches") self.add_key.focus_set() self.add_key.bind("<KeyPress>", self.on_key_add) self.add_key.protocol("WM_DELETE_WINDOW", self.on_closing_add_key) def on_key_add(self, event): if event.keycode in self.dict_key.values(): pass else: self.dict_key[self.n] = event.keycode self.n += 1 self.text.set("Vous avez actuellement ajouté {} touches".format( self.n)) def on_closing_add_key(self): self.add_key.unbind("<KeyPress>") self.add_key.destroy() def erase_team(self): """ Fonction qui crée une nouvelle fenêtre dans laquelle on peut effacer des équipes. bouton("Effacer une équipe") :return: """ self.list_team_to_erase = Toplevel(self.Obj_Window_General_Function) self.list_team_to_erase.focus_set() self.list_team_to_erase.grab_set() label = tk.Label( self.list_team_to_erase, text="Sélectionner une équipe à effacer et fermer la fenêtre") label.pack() self.dict_check_button_team = {} for i in self.list_team: var = BooleanVar(self) self.dict_check_button_team[i] = var chk = Checkbutton(self.list_team_to_erase, text=i, variable=var) chk.pack() self.list_team_to_erase.protocol("WM_DELETE_WINDOW", self.on_closing) self.list_team_to_erase.mainloop() def on_closing(self): """ fonction qui s'éxcute lorsqu'on ferme la fenêtre "erase_team" :return: """ for chk in self.dict_check_button_team.keys(): if self.dict_check_button_team[chk].get() == True: self.list_team.remove(chk) else: pass self.list_team_to_erase.destroy()
def csd_guess(): #Maybe insert parameter here to tell to write LM fit def quit_window(): root.destroy() def fetch(): global csd, fixed try: csd = {} #Reset the csd to plot fixed = {} val = [] for row in rows: j = 0 for column in row: if j == 0: val.append(str(column.get())) #Add ion if j == 1: if float(column.get()) < 0: messagebox.showwarning( 'Invalid parameter.', 'Charge-state de' + 'nsity must be a positive number. Ther' + 'e will be a reset.') redo_form() else: val.append(float(column.get())) #Add csd if j == 2: val.append(column.val.get() ) #Add fixed parameter for LM fit j += 1 for p in power: csd['power'] = float(p.get()) except: messagebox.showerror( 'Invalid parameter', 'One input is not a number.' + ' Parameters will reset.') redo_form() return #Solved a loop messagebox error csd_changed.set(True) for j in range(len(rows)): csd[val[3 * j]] = val[3 * j + 1] fixed[val[3 * j]] = val[3 * j + 2] ask_plot() def add_row(): global i i = i + 1 items = [] for j in range(0, 2): #Columns b = Entry(root, width=10) items.append(b) b.grid(row=i, column=j) var = IntVar() c = Checkbutton(root, variable=var, width=10, anchor='w') c.val = var items.append(c) c.grid(row=i, column=2) rows.append(items) def delete_row(): for rowno, row in reversed(list(range(len(rows)))): for i in row: i.destroy() rows.pop(rowno) break def redo_form(): global csd, csd_standard csd = csd_standard for rowno, row in reversed(list(range(len(rows)))): for i in row: i.destroy() rows.pop(rowno) make_form(root) fetch() def make_form(root): global csd, i, fixed, fixed_standard, power, rows ions = list(csd.keys())[1:] #To ignore power csds = list(csd.values())[1:] fixeds = list(fixed_standard.values()) rows = [] power = [] for k in range(len(ions)): i = i + 1 items = [] for j in range(0, 2): #Columns b = Entry(root, width=10) if j == 0: b.insert(j, ions[k]) else: b.insert(j, csds[k]) items.append(b) b.grid(row=i, column=j) var = IntVar() var.set(fixeds[k]) #To already have checked buttons c = Checkbutton(root, variable=var, width=10, anchor='w') c.val = var items.append(c) c.grid(row=i, column=2) rows.append(items) e3 = Entry(root, width=5) e3.insert(0, csd.get('power')) e3.grid(row=1, column=2, padx=5, pady=5, sticky='e') power.append(e3) e4 = Label(root, text='Power 1e+', width=8) e4.grid(row=1, column=2, padx=5, pady=5, sticky='w') #CSD guess main #-------------------------------------------------------------------------- #global csd_standard, i, ions, csds, fixed, rows, power root = Toplevel() root.title('Charge-state distribution') #root.iconbitmap(r'favico.ico') make_form(root) b1 = ttk.Button(root, text='Save', command=fetch) b1.grid(row=0, column=0) root.bind('<Return>', lambda events: fetch() ) #If presses enter, it saves ('presses' b1 button) b2 = ttk.Button(root, text='Reset', command=redo_form) b2.grid(row=0, column=1) b3 = ttk.Button(root, text='Quit', command=quit_window) b3.grid(row=0, column=2) bt = ttk.Button(root, text='Add row', command=add_row) bt.grid(row=1, column=0) dl = ttk.Button(root, text='Delete row', command=delete_row) dl.grid(row=1, column=1) e0 = Label(root, text='Ion') e0.grid(row=2, column=0) e1 = Label(root, text='CSD (ion/cm3)') e1.grid(row=2, column=1) e2 = Label(root, width=15, text='LM fixed', anchor='w') e2.grid(row=2, column=2) root.mainloop()
class Maze: grid = [] solution = {} number_solution = 1 def __init__(self, m=1, n=1, parent=None, x_start=None, y_start=None, x_finish=None, y_finish=None): self.window = Toplevel(parent) self.canvas = Canvas(self.window, width=(n + 2) * WIDTH_HOL, height=(m + 2) * WIDTH_HOL, bg="blue") self.initialize_window(m) self.draw_maze(m, n) self.create_maze(x_start, y_start) self.draw_solution_plot(x_finish, y_finish, x_start, y_start) self.check_solution(x_finish, y_finish, x_start, y_start) self.hero = self.canvas.create_oval( (x_start + 3, y_start + 3, x_start + WIDTH_HOL - 6, y_start + WIDTH_HOL - 6), fill="#000000") self.x_hero = x_start self.y_hero = y_start self.x_finish = x_finish self.y_finish = y_finish self.window.mainloop() def initialize_window(self, m): """ Tworzenie okna oraz przycisków """ self.window.title("Maze") self.window.geometry("{}x{}".format(WIDTH, HEIGHT)) self.window.resizable(width=False, height=False) self.window.bind("<KeyPress-Left>", lambda _: self.hero_left()) self.window.bind("<KeyPress-Right>", lambda _: self.hero_right()) self.window.bind("<KeyPress-Up>", lambda _: self.hero_up()) self.window.bind("<KeyPress-Down>", lambda _: self.hero_down()) button_close = Button(self.window, text="Close Project", width=20, command=self.close_maze) button_close.pack(side=BOTTOM) self.canvas.place(x=(WIDTH - (m + 2) * WIDTH_HOL) / 2, y=HEIGHT / 8) label = Label(self.window, text="Labirynt", justify=CENTER) label.pack(side=TOP) self.win = StringVar("") win_label = Label(self.window, textvariable=self.win, font=("Times New Roman", 14)) win_label.pack(side=TOP) def check_coordinate_hero(self, a, b, a1, b1): """ Sprawdzenie lini w koło kuli ktora jest naszą postacią """ if self.canvas.find_overlapping(self.x_hero + a, self.y_hero + b, self.x_hero + a1, self.y_hero + b1) == (): return True else: return False def hero_up(self): """ Przesunięcie postaci w gorę labiryntu oraz sprawdzenie czy koniec labirytu """ if self.check_coordinate_hero(2, -2, 4, 2): self.y_hero -= WIDTH_HOL self.canvas.move(self.hero, 0, -WIDTH_HOL) if (self.x_hero == self.x_finish) and (self.y_hero == self.y_finish): self.win.set("Doszedłeś do końca") self.window.update() def hero_down(self): """ Przesunięcie postaci w dół labiryntu oraz sprawdzenie czy koniec labirytu """ if self.check_coordinate_hero(2, WIDTH_HOL + 2, 4, WIDTH_HOL - 2): self.y_hero += WIDTH_HOL self.canvas.move(self.hero, 0, WIDTH_HOL) if (self.x_hero == self.x_finish) and (self.y_hero == self.y_finish): self.win.set("Doszedłeś do końca") self.window.update() def hero_left(self): """ Przesunięcie postaci w lewą stronę labiryntu oraz sprawdzenie czy koniec labirytu """ if self.check_coordinate_hero(-2, 4, 2, 6): self.x_hero -= WIDTH_HOL self.canvas.move(self.hero, -WIDTH_HOL, 0) if (self.x_hero == self.x_finish) and (self.y_hero == self.y_finish): self.win.set("Doszedłeś do końca") self.window.update() def hero_right(self): """ Przesunięcie postaci w prawą stronę labiryntu oraz sprawdzenie czy koniec labirytu """ if self.check_coordinate_hero(WIDTH_HOL + 2, 2, WIDTH_HOL - 2, 4): self.x_hero += WIDTH_HOL self.canvas.move(self.hero, WIDTH_HOL, 0) if (self.x_hero == self.x_finish) and (self.y_hero == self.y_finish): self.win.set("Doszedłeś do końca") self.window.update() def draw_maze(self, m, n): """ Rysowanie pustej siatki o zadanych wymiarach """ y = WIDTH_HOL for i in range(1, m + 1): x = WIDTH_HOL for j in range(1, n + 1): if check_coordinate_line(self.canvas, x, y, 2, -2, 4, 2): self.canvas.create_line((x, y, x + WIDTH_HOL, y), width=2) if check_coordinate_line(self.canvas, x, y, WIDTH_HOL + 2, 2, WIDTH_HOL - 2, 4): self.canvas.create_line( (x + WIDTH_HOL, y, x + WIDTH_HOL, y + WIDTH_HOL), width=2) if check_coordinate_line(self.canvas, x, y, 2, WIDTH_HOL + 2, 4, WIDTH_HOL - 2): self.canvas.create_line( (x, y + WIDTH_HOL, x + WIDTH_HOL, y + WIDTH_HOL), width=2) if check_coordinate_line(self.canvas, x, y, -2, 4, 2, 6): self.canvas.create_line((x, y, x, y + WIDTH_HOL), width=2) self.window.update() self.grid.append((x, y)) x = x + WIDTH_HOL y = y + WIDTH_HOL def create_maze(self, x, y): """ Tworzenie korytarzy poprzez usuwanie lini """ stack = [(x, y)] visited = [(x, y)] while len(stack) > 0: cell = [] if (x + WIDTH_HOL, y) not in visited and (x + WIDTH_HOL, y) in self.grid: cell.append("right") if (x - WIDTH_HOL, y) not in visited and (x - WIDTH_HOL, y) in self.grid: cell.append("left") if (x, y + WIDTH_HOL) not in visited and (x, y + WIDTH_HOL) in self.grid: cell.append("down") if (x, y - WIDTH_HOL) not in visited and (x, y - WIDTH_HOL) in self.grid: cell.append("up") if len(cell) > 0: cell_chosen = (random.choice(cell)) if cell_chosen == "right": self.clear_line(x + WIDTH_HOL + 2, y + 2, x + WIDTH_HOL - 2, y + 4) self.solution[(x + WIDTH_HOL, y)] = x, y x = x + WIDTH_HOL elif cell_chosen == "left": self.clear_line(x - 2, y + 4, x + 2, y + 6) self.solution[(x - WIDTH_HOL, y)] = x, y x = x - WIDTH_HOL elif cell_chosen == "down": self.clear_line(x + 2, y + WIDTH_HOL + 2, x + 4, y + WIDTH_HOL - 2) self.solution[(x, y + WIDTH_HOL)] = x, y y = y + WIDTH_HOL elif cell_chosen == "up": self.clear_line(x + 2, y - 2, x + 4, y + 2) self.solution[(x, y - WIDTH_HOL)] = x, y y = y - WIDTH_HOL visited.append((x, y)) stack.append((x, y)) else: x, y = stack.pop() def clear_line(self, x1, y1, x2, y2): """ Sprawdzenie czy na danej pozycji jest obiekt(linia) a pożniej jej usuniecie """ line = self.canvas.find_overlapping(x1, y1, x2, y2) self.canvas.delete(line) self.window.update() def draw_solution_cell(self, x, y, x_finish, y_finish): """ Rysowanie małego kulka """ if x == x_finish and y == y_finish: self.canvas.create_rectangle( (x + 6, y + 6, x + WIDTH_HOL - 6, y + WIDTH_HOL - 6), fill="#00ff00", width=0) else: self.canvas.create_oval( (x + 8, y + 8, x + WIDTH_HOL - 8, y + WIDTH_HOL - 8), fill="#00ff00", width=0) self.window.update() def draw_solution_plot(self, x_finish, y_finish, x_start, y_start): """ Rysowanie rozwiązania w labiryncie """ x, y = x_finish, y_finish self.draw_solution_cell(x, y, x_finish, y_finish) while (x, y) != (x_start, y_start): x, y = self.solution[x, y] self.draw_solution_cell(x, y, x_finish, y_finish) self.number_solution += 1 def close_maze(self): """ Obsługa przycisku zakończenia """ self.window.destroy() def check_solution(self, x_finish, y_finish, x_start, y_start): """ Funkcja służy do sprawdzana czy rozwiązanie jest drogą prostą """ ilosc_x = 1 ilosc_y = 1 x, y = x_finish, y_finish while (x, y) != (x_start, y_start): x, y = self.solution[x, y] if x == x_start: ilosc_x += 1 print("ilosc_x", ilosc_x, self.number_solution) if (self.number_solution == ilosc_x): self.win.set("Labirynt jest droga prosta") self.window.update() if y == y_start: ilosc_y += 1 if (self.number_solution == ilosc_y): self.win.set("Labirynt jest droga prosta") self.window.update()
def off_two_grabber(): check_off.set( 'TwoPoints' ) #This forces equation to set as default in case user doesn't choose two points if plot_done.get() or load_var.get( ) != '': #If there is plot or exp data, you can click to get inclination try: for t in spectrum.texts: t.set_visible( False) #Removes x marks to prepare for new offset spectrum.grid(b=True, which='both', axis='both') f.canvas.draw() def onclick(event): #On click it saves the coordinates ix, iy = float(event.xdata), float(event.ydata) global coords coords.append((ix, iy)) spectrum.text(ix, iy, 'x', ha='center', va='center') #Draws an 'x' f.canvas.draw() if len( coords ) == 2: #Once it saves two clicks, disconnects the mouse f.canvas.mpl_disconnect(cid) spectrum.grid( False) #Gets rid of grids and saves coordenates spectrum.grid(False, which='minor') f.canvas.draw() x1 = coords[0][0] y1 = coords[0][1] x2 = coords[1][0] y2 = coords[1][1] param_m.set((y2 - y1) / (x2 - x1)) param_b.set(y2 - param_m.get() * x2) for t in spectrum.texts: t.set_visible(False) #Gets rid of the 'x's coords = [] ask_plot() cid = f.canvas.mpl_connect('button_press_event', onclick) except Exception as ex: print( 'Exception thrown whilst obtaining/applying the offset.' + ex) messagebox.showerror('Error', 'Something went wrong with the offset.') else: #If there is no plot or no data, it opens a new window fields = ['m', 'b'] defaults = [0, .7] def quit_window(): root.destroy() def fetch(entries): val = [] for entry in entries: try: val.append(float(entry.get())) except: messagebox.showerror( 'Invalid parameter', 'One input is not a num' + 'ber. Parameters will reset.') redo_form(entries) param_m.set(val[0]) param_b.set(val[1]) ask_plot() def make_form(root, fields): entries = [] row = Frame(root) lab = Label(row, width=36, text='With no plot, choose y=mx+b paramete' + 'rs.', anchor='w') row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) row = Frame(root) lab = Label(row, width=5, text=fields[0], anchor='w') ent = Entry(row) ent.insert(0, defaults[0]) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append(ent) row = Frame(root) lab = Label(row, width=5, text=fields[1], anchor='w') ent = Entry(row) ent.insert(0, defaults[1]) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append(ent) return entries def redo_form(entries): i = 0 for entry in entries: entry.delete(0, END) entry.insert(0, defaults[i]) i += 1 fetch(entries) #Offset submain #------------------------------------------------------------------------ root = Toplevel() root.title('Offset points') #root.iconbitmap(r'favico.ico') ents = make_form(root, fields) b1 = ttk.Button(root, text='Save', command=(lambda e=ents: fetch(e))) b1.pack(side=LEFT, padx=5, pady=5) root.bind('<Return>', lambda events, e=ents: fetch(e) ) #If presses enter, it saves ('presses' b1 button) b2 = ttk.Button(root, text='Reset', command=(lambda e=ents: redo_form(e))) b2.pack(side=LEFT, padx=5, pady=5) b3 = ttk.Button(root, text='Quit', command=quit_window) b3.pack(side=LEFT, padx=5, pady=5)
class Journal(): def __init__(self, master): with open('config.json', 'r') as file: self.config = json.load(file) master.title('My Journal') master.configure(background=self.config['master']) master.resizable(False, False) # TODO # add checklist style = ttk.Style() style.configure('TEntry', foreground=self.config['entry']['foreground'], fieldbackground=self.config['entry']['background'], font=(self.config['entry']['font'], self.config['entry']['font_size'] ) ) style.configure('main.TLabel', background=self.config['label']['background'], foreground=self.config['label']['foreground'], font=(self.config['label']['font'], self.config['label']['font_size'] ) ) ttk.Label(master, text='Location: ', style='main.TLabel').grid( row=1, column=0, padx=2, pady=3) self.location_entry = ttk.Entry(master, width=100) self.location_entry.grid(row=1, column=2, padx=2, pady=3) self.refresh_location_button = HoverButton(master, text="Refresh", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.refresh_location()) self.refresh_location_button.grid(row=1, column=3, padx=2, pady=3) # self.text_frame = ttk.Frame(master, width=100, height=100) # self.text_frame.grid(row=2, column=0, columnspan=2) self.text_entry = Text( master, height=30, wrap='word', background=self.config['text_field']['background'], foreground=self.config['text_field']['foreground'], font=(self.config['text_field']['font'], self.config['text_field']['font_size']) ) self.text_entry.grid(row=2, column=0, columnspan=4, sticky='NESW', padx=2, pady=5) self.submit_button = HoverButton(master, text="Submit", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.submit()) self.submit_button.grid( row=3, column=0, sticky='NE', padx=2, pady=5) self.clear_button = HoverButton(master, text="Clear", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.clear()) self.clear_button.grid(row=3, column=1, sticky='NW', padx=10, pady=5) self.about_button = HoverButton(master, text="About", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.show_help()) self.about_button.grid(row=3, column=2, sticky='NE', padx=10, pady=5) self.customise_button = HoverButton(master, text="Customise Colors", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.customize(master)) self.customise_button.grid( row=3, column=3, sticky='NE', padx=10, pady=5) menubar = Menu(master) filemenu = Menu(menubar, tearoff=0) filemenu.add_command( label=' Submit', command=lambda: self.submit(), accelerator='Ctrl+Enter') filemenu.add_separator() filemenu.add_command( label=' Exit', command=lambda: master.quit(), accelerator='Ctrl+X') menubar.add_cascade(label='File', menu=filemenu) master.config(menu=menubar) self.refresh() # self.refresh_location() # keyboard bindings master.bind('<Control-Return>', lambda e: self.submit()) master.bind('<Control-x>', lambda e: master.quit()) self.text_entry.focus() def refresh(self): self.text_entry.delete(1.0, 'end') self.text_entry.insert(1.0, 'Journal Entry Here!') def refresh_location(self): g = geocoder.ip('me') logging.debug(print(g)) self.location_entry.delete(0, 'end') if g: self.location_entry.insert(0, f'{g.city} lat:{g.latlng[0]} lng:{g.latlng[1]}' ) else: self.location_entry.insert(0, 'Enter location') def submit(self): text = self.text_entry.get(1.0, 'end') self.string_text = f"datetime : {datetime.now().strftime('%H:%M:%S %d-%m-%Y')}\nlocation : {self.location_entry.get()}\nentry: {text}\n" self.save_to_file() self.clear() def save_to_file(self): self.filename = filedialog.asksaveasfilename( filetypes=(("Text File", "*.txt"),)) logging.debug(type(self.filename)) logging.debug(self.filename) if isinstance(self.filename, str): with open(self.filename, 'a') as file: logging.debug(f'wrote {self.string_text} to {self.filename}') file.write(self.string_text) messagebox.showinfo( title='Info', message=f'saved to {self.filename}') else: pass def clear(self): self.refresh() self.location_entry.delete(0, 'end') self.text_entry.delete(1.0, 'end') def show_help(self): messagebox.showinfo(title='Help', message='My Journal helps you to arrange your journal entries along with timestamp and\ location. Once you submit, new journal entry will be appended to the file selected.\ \n\nLocation is fetched based on the IP.') def customize(self, master): self.cust_window = Toplevel(master) self.cust_window.config(background=master['background']) self.cust_window.bind('<Return>', lambda e: self.write_config()) ttk.Label(self.cust_window, text='Main Background:', style='main.TLabel').grid(row=0, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Entry Background:', style='main.TLabel').grid( row=1, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Entry Foreground:', style='main.TLabel').grid( row=2, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Label Background:', style='main.TLabel').grid( row=3, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Label Foreground:', style='main.TLabel').grid( row=4, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Button Background:', style='main.TLabel').grid( row=5, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Button Foreground:', style='main.TLabel').grid( row=6, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Journal Entry Background:', style='main.TLabel').grid( row=7, column=0, padx=2, pady=2) ttk.Label(self.cust_window, text='Journal Entry Foreground:', style='main.TLabel').grid( row=8, column=0, padx=2, pady=2) self.main_background = ttk.Entry(self.cust_window) self.entry_background = ttk.Entry(self.cust_window) self.entry_foreground = ttk.Entry(self.cust_window) self.label_background = ttk.Entry(self.cust_window) self.label_foreground = ttk.Entry(self.cust_window) self.button_background = ttk.Entry(self.cust_window) self.button_foreground = ttk.Entry(self.cust_window) self.journal_background = ttk.Entry(self.cust_window) self.journal_foreground = ttk.Entry(self.cust_window) self.main_background.grid(row=0, column=1) self.entry_background.grid(row=1, column=1) self.entry_foreground.grid(row=2, column=1) self.label_background.grid(row=3, column=1) self.label_foreground.grid(row=4, column=1) self.button_background.grid(row=5, column=1) self.button_foreground.grid(row=6, column=1) self.journal_background.grid(row=7, column=1) self.journal_foreground.grid(row=8, column=1) # self.submit_config = ttk.Button(self.cust_window, text='Submit', command=lambda:self.write_config()) self.submit_config = HoverButton(self.cust_window, text="Submit", background=self.config['button']['background'], foreground=self.config['button']['foreground'], command=lambda: self.write_config()) self.submit_config.grid(row=9, column=0) self.populate_entries() def write_config(self): self.config['master'] = self.main_background.get() self.config['entry']['background'] = self.entry_background.get() self.config['entry']['foreground'] = self.entry_foreground.get() self.config['label']['background'] = self.label_background.get() self.config['label']['foreground'] = self.label_foreground.get() self.config['button']['background'] = self.button_background.get() self.config['button']['foreground'] = self.button_foreground.get() self.config['text_field']['background'] = self.journal_background.get() self.config['text_field']['foreground'] = self.journal_foreground.get() with open('config.json', 'w') as file: json.dump(self.config, file) messagebox.showinfo( title='Info', message='Please restart the application for the changes to take effect') self.cust_window.quit() def populate_entries(self): self.clear_entries() self.main_background.insert(0, self.config['master']) self.entry_background.insert(0, self.config['entry']['background']) self.entry_foreground.insert(0, self.config['entry']['foreground']) self.label_background.insert(0, self.config['label']['background']) self.label_foreground.insert(0, self.config['label']['foreground']) self.button_background.insert(0, self.config['button']['background']) self.button_foreground.insert(0, self.config['button']['foreground']) self.journal_background.insert( 0, self.config['text_field']['background']) self.journal_foreground.insert( 0, self.config['text_field']['foreground']) def clear_entries(self): self.main_background.delete(0, 'end') self.entry_background.delete(0, 'end') self.entry_foreground.delete(0, 'end') self.label_background.delete(0, 'end') self.label_foreground.delete(0, 'end') self.button_background.delete(0, 'end') self.button_foreground.delete(0, 'end') self.journal_background.delete(0, 'end') self.journal_foreground.delete(0, 'end')
def askFilename(self): currdir = os.getcwd() filey = None filey = filedialog.askopenfilename(parent=self.master, initialdir=currdir, title='Select burn file') if type(filey) == str and filey != '': self.entryVar.set(filey) try: if not (str(self.entryVar.get()).split(".")[1] == "xls" or str(self.entryVar.get()).split(".")[1] == "XLS" or str(self.entryVar.get()).split(".")[1] == "xlsx" or str(self.entryVar.get()).split(".")[1] == "XLSX"): posx = 500 posy = 400 sizex = 500 sizey = 100 top = Toplevel() top.title("Wrong file type") top.grid_rowconfigure(0,weigh=1) top.grid_columnconfigure(0, weight=1) top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) msg = Message(top, text="You selected a wrong file type.\nPlease use xls or xlsx.", width=300, anchor=CENTER) msg.grid(row=0, column=0) button = Button(top,text="Ok", command=top.destroy) button.grid(row=1, column=0) self.entryVar.set("") self.current_window = top if self.runningInFrozen: top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico") else: top.iconbitmap("emblem_print.ico") top.focus_force() top.bind("<FocusOut>", self.Alarm) return None except: posx = 500 posy = 400 sizex = 500 sizey = 100 top = Toplevel() top.title("Wrong file type") top.grid_rowconfigure(0,weigh=1) top.grid_columnconfigure(0, weight=1) top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) msg = Message(top, text="You selected a wrong file type.\nPlease use xls or xlsx.", width=300, anchor=CENTER) msg.grid(row=0, column=0) button = Button(top,text="Ok", command=top.destroy) button.grid(row=1, column=0) self.entryVar.set("") top.focus_force() if self.runningInFrozen: top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico") else: top.iconbitmap("emblem_print.ico") self.current_window = top top.bind("<FocusOut>", self.Alarm) return None else: return None temp = readExcel(str(self.entryVar.get())) orderedExcelInfo = sortPartNumberList(temp[0],temp[1]) temp = findPDFs(orderedExcelInfo) #The xlsx library is not reading the data correctly. #for dictx in orderedExcelInfo: # print (dictx) self.PDFs = temp [0] self.unfoundItems = temp[1] self.wrongRevsion = temp[2] #Populate the text fields self.text_found_files_body.configure(state=NORMAL) self.text_unfound_files_body.configure(state=NORMAL) self.text_revision_body.configure(state=NORMAL) self.text_found_files_body.delete('0.0', END) self.text_unfound_files_body.delete('0.0', END) self.text_revision_body.delete('0.0', END) counter = 1 for pdf in self.PDFs: self.text_found_files_body.insert(str(counter)+'.0',str(counter)+". "+pdf.replace("\"","")+"\n") counter += 1 #print (counter) self.totalFiles = counter counter = 1 for part in self.unfoundItems: self.text_unfound_files_body.insert(str(counter)+'.0', str(counter)+". "+part.replace("\"","")+"\n") counter += 1 counter = 1 for part in self.wrongRevsion: self.text_revision_body.insert(str(counter)+'.0',str(counter)+". "+part.replace("\"","")+"\n") counter += 1 self.text_found_files_body.configure(state=DISABLED) self.text_unfound_files_body.configure(state=DISABLED) self.text_revision_body.configure(state=DISABLED)
class Game: """ Main class that includes all methods that are required to start a new round of '2048' in a tkinter gui. """ def __init__(self): """ Method to get a new instance of the game class with a new gui window. """ self.root = Tk() self.colors = {0:"AntiqueWhite2", 2:"AntiqueWhite1", 4:"bisque2", 8:"sandy brown", 16:"chocolate1", 32:"tomato", 64:"orange red", 128:"light goldenrod", 256:"light goldenrod", 512:"light goldenrod", 1024:"yellow2", 2048:"gold"} self.directions = {"d": 3, "l": 2, "u": 1, "r": 0} self.get_start_field() self.get_labels() self.grid_labels() self.init_bindings() # window width x window height + position right + position down self.root.geometry("+300+300") self.root.title("2048") self.root.configure(background="AntiqueWhite3") self.root.mainloop() def key_return(self, event): """ Handles the event that the return key is pressed within the popup window (if the game is over). """ widget = self.popup.focus_get() btn_text = widget.config('text')[-1] if btn_text in ("Restart", "Quit"): widget.invoke() def key_pressed(self, direction): """ Handles the event that an arrow key is pressed within the main window. """ if self.get_next_field(direction): if not self.zero_exists(): self.show_popup() else: self.add_number() self.get_labels() self.grid_labels() if self.game_over(): self.show_popup() def show_popup(self): """ Opens a popup window if the game is over to ask for a new game or to quit. """ self.remove_bindings() self.popup = Toplevel(self.root) self.popup.wm_title("Game over") lbl = Label(self.popup, text="This game is over!", font=("Arial", 10)) lbl.grid(row=0, column=0, columnspan=2, sticky=W+E+S, padx=100, pady=10) btn1 = Button(self.popup, text="Restart", font=("Arial", 10), command=self.restart_game, width=10, bd=3) btn1.focus_set() btn1.grid(row=1, column=0, sticky=E+N, padx=10, pady=10) btn2 = Button(self.popup, text="Quit", font=("Arial", 10), command=self.root.quit, width=10, bd=3) btn2.grid(row=1, column=1, sticky=W+N, padx=10, pady=10) self.popup.attributes('-topmost', True) self.popup.bind('<Return>', self.key_return) self.popup.geometry("+350+350") def restart_game(self): """ Closes the popup window and starts a new round of the game in the main window. """ self.get_start_field() self.get_labels() self.grid_labels() self.popup.unbind('<Return>') self.popup.destroy() self.popup.update() self.init_bindings() def zero_exists(self): """ Checks whether there is at least one zero in the field. """ for col in range(4): for row in range(4): if self.field[col][row] == 0: return True return False def game_over(self): """ Checks whether the game is over yet, i.e. there are no equivalent numbers adjacent to each other and furthermore there are no zeros (no free space) on the field. """ for col in range(3): for row in range(4): if self.field[col][row] == self.field[col + 1][row]: return False for col in range(4): for row in range(3): if self.field[col][row] == self.field[col][row + 1]: return False return not self.zero_exists() def add_number(self): """ Adds a 2 or a 4 to a random free coordinate on the field. """ while True: col = random.randint(0, 3) row = random.randint(0, 3) if self.field[col][row] == 0: break self.field[col][row] = random.randint(1, 2) * 2 @staticmethod def rotate_field_right_once(field): """ Rotates the whole field 90 degrees to the right. """ field_t = [] for col in range(4): field_t.append([0, 0, 0, 0]) for col in range(4): for row in range(4): field_t[row][3-col] = field[col][row] return field_t def rotate_field_right(self, field, direction, after_move=False): """ Rotates the whole field multiple times to the right. The rotation is called recursively dependend on the direction (the arrow key that was pressed). If the optional parameter 'after_move' is True, the rotation is called after moving the numbers to the right, i.e. the field was rotated before the move already and has to be rotated to its original orientation now. While the direction equals the key that was initially pressed, the number of rotation changes if after_move is True. """ if after_move and direction in ("u", "d"): direction = "u" if direction == "d" else "d" rotations_to_go = self.directions[direction] if rotations_to_go == 0: return field field_rotated = self.rotate_field_right_once(field) directions = {y:x for x, y in self.directions.items()} return self.rotate_field_right(field_rotated, directions[rotations_to_go - 1]) def get_next_field(self, direction): """ Calculates the next field after moving all numbers to a given direction. The central logic for moving and merging the numbers on the field is written for the case, that direction is equal to 'r' (right). If the direction is not equal to 'r', the field is rotated, then the moving and merging is executed on the rotated field and finally the field is rotated again to its original orientation. If the new field is different to the input field, the function returns True and updates the field variable of the game class. """ field = copy.copy(self.field) field = self.rotate_field_right(field, direction) field = self.move_field_right(field) field = self.rotate_field_right(field, direction, True) if field == self.field: return False self.field = field return True def move_field_right(self, field): """ Move all numbers of the given field to the right direction and merge adjacent equivalent numbers. Calculate the new field row by row (divide & conquer). """ for row in range(4): field[row] = self.move_row_right(field[row]) return field @staticmethod def move_row_right(row): """ Move all numbers of the given row to the right direction and merge adjacent equivalent numbers. """ row_new = [] for col in range(3, -1, -1): if row[col] != 0: row_new.append(row[col]) while len(row_new) != 4: row_new.append(0) row_new = list(reversed(row_new)) if row_new[2] == row_new[3]: row_new[3] *= 2 if row_new[0] == row_new[1]: row_new[2] = row_new[1] * 2 row_new[1] = 0 else: row_new[2] = row_new[1] row_new[1] = row_new[0] row_new[0] = 0 elif row_new[1] == row_new[2]: row_new[1] = row_new[0] row_new[0] = 0 row_new[2] *= 2 elif row_new[0] == row_new[1]: row_new[1] *= 2 row_new[0] = 0 return row_new def quit(self, event): """ Quits the application. """ self.root.destroy() def init_bindings(self): """ Initializes the bindings for all keys that have a correspondent function. """ self.root.bind('<Escape>', self.quit) self.root.bind('<Left>', lambda event, k="l": self.key_pressed(k)) self.root.bind('<Right>', lambda event, k="r": self.key_pressed(k)) self.root.bind('<Up>', lambda event, k="u": self.key_pressed(k)) self.root.bind('<Down>', lambda event, k="d": self.key_pressed(k)) def remove_bindings(self): """ Removes all bindings (except the escape command) to freeze the main window if the game is over. """ self.root.unbind('<Left>') self.root.unbind('<Right>') self.root.unbind('<Up>') self.root.unbind('<Down>') def get_start_field(self): """ Returns a new field with 4 numbers height and width filled with zeros and two random numbers. """ field = [] for col in range(4): field.append([]) for _ in range(4): field[col].append(0) self.field = field for _ in range(2): self.add_number() def get_labels(self): """ Updates the dict of the main class that contains one label for each number of the field. Each label is saved with the name 'l00' where the first digit is the row and the second digit is the column of the label. After updating the labels they can be rendered via the grid function. """ labels = {} for col in range(4): for row in range(4): font = ("Arial", 20) height = 2 width = 4 if self.field[col][row] == 0: labels["l" + str(col) + str(row)] = Label( self.root, fg=self.colors[0], bg=self.colors[0], text="0", font=font, height=height, width=width) else: labels["l" + str(col) + str(row)] = Label( self.root, bg=self.colors[min( self.field[col][row], list(self.colors.keys())[-1])], text=str(self.field[col][row]), font=font, height=height, width=width) self.labels = labels def grid_labels(self): """ Updates the grid and places all labels of the dict into the grid at the position that is given with the dictionarys keys. """ for row in range(4): for col in range(4): self.labels["l" + str(row) + str(col)].grid( row=row, column=col, padx=3, pady=3)
'rank': rank, 'bonus': bonus, 'invite': invite, 'ratio': ratio, 'upload': upload, 'download': download } root = Tk() root.title('BYRBT TOOL') # makeMainPanel(root) LoginPanel = Toplevel() LoginPanel.title('LoginPanel') makeLoginPanel(LoginPanel) root.withdraw() def callback(event): print('ready to deiconify') root.deiconify() print('root has deiconifyed') makeMainPanel(root) LoginPanel.unbind("<Destroy>", funcid) funcid = LoginPanel.bind("<Destroy>", callback) root.mainloop()
class winlog(): """readonly modaless Toplevel log window class""" def __init__(self, root, title='Log Window', withdrawRoot=False, destroyRoot=False): self.root = root if withdrawRoot: self.root.withdraw() self.win = Toplevel(root) self.win.title(title) self.win.geometry('600x800') self.frame_0 = tk.Frame(self.win) self.frame_0.pack(fill='both', expand=True) self.st = tklog(master=self.frame_0, height=0) self.st.pack(fill='both', expand=True) self.frame_1 = tk.Frame(self.win) self.frame_1.pack(fill=tk.X) self.top = tk.Button(self.frame_1, text='Pin', command=self._pin) self.top.pack(side=tk.LEFT, padx=2, pady=2) self.win.bind('<FocusIn>', self._focusIn) self.win.bind('<FocusOut>', self._focusOut) self.pin = 0 # default is unpinned self.win.protocol('WM_DELETE_WINDOW', self.destroy) self.destroyRoot = destroyRoot def _focusIn(self, event): self.win.attributes('-alpha', 1.0) def _focusOut(self, event): self.win.attributes('-alpha', 0.7) def _pin(self): if self.pin == 0: self.win.attributes('-topmost', True) self.pin = 1 self.top['text'] = 'Unpin' elif self.pin == 1: self.win.attributes('-topmost', False) self.pin = 0 self.top['text'] = 'Pin' def title(self, content, end='\n'): self.st.title(content, end) def info(self, content, end='\n'): self.st.log(content, end) log = info def debug(self, content, end='\n'): self.st.debug(content, end) def warning(self, content, end='\n'): self.st.warning(content, end) def error(self, content, end='\n'): self.st.error(content, end) def critical(self, content, end='\n'): self.st.critical(content, end) def png(self, pngFile): self.st.png(pngFile) def gif(self, gifFile): self.st.gif(gifFile) def destroy(self): self.win.destroy() if self.destroyRoot: self.root.destroy()
class FileDialog: """Standard file selection dialog -- no checks on selected file. Usage: d = FileDialog(master) fname = d.go(dir_or_file, pattern, default, key) if fname is None: ...canceled... else: ...open file... All arguments to go() are optional. The 'key' argument specifies a key in the global dictionary 'dialogstates', which keeps track of the values for the directory and pattern arguments, overriding the values passed in (it does not keep track of the default argument!). If no key is specified, the dialog keeps no memory of previous state. Note that memory is kept even when the dialog is canceled. (All this emulates the behavior of the Macintosh file selection dialogs.) """ title = "File Selection Dialog" def __init__(self, master, title=None): if title is None: title = self.title self.master = master self.directory = None self.top = Toplevel(master) self.top.title(title) self.top.iconname(title) self.botframe = Frame(self.top) self.botframe.pack(side=BOTTOM, fill=X) self.selection = Entry(self.top) self.selection.pack(side=BOTTOM, fill=X) self.selection.bind('<Return>', self.ok_event) self.filter = Entry(self.top) self.filter.pack(side=TOP, fill=X) self.filter.bind('<Return>', self.filter_command) self.midframe = Frame(self.top) self.midframe.pack(expand=YES, fill=BOTH) self.filesbar = Scrollbar(self.midframe) self.filesbar.pack(side=RIGHT, fill=Y) self.files = Listbox(self.midframe, exportselection=0, yscrollcommand=(self.filesbar, 'set')) self.files.pack(side=RIGHT, expand=YES, fill=BOTH) btags = self.files.bindtags() self.files.bindtags(btags[1:] + btags[:1]) self.files.bind('<ButtonRelease-1>', self.files_select_event) self.files.bind('<Double-ButtonRelease-1>', self.files_double_event) self.filesbar.config(command=(self.files, 'yview')) self.dirsbar = Scrollbar(self.midframe) self.dirsbar.pack(side=LEFT, fill=Y) self.dirs = Listbox(self.midframe, exportselection=0, yscrollcommand=(self.dirsbar, 'set')) self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) self.dirsbar.config(command=(self.dirs, 'yview')) btags = self.dirs.bindtags() self.dirs.bindtags(btags[1:] + btags[:1]) self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event) self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event) self.ok_button = Button(self.botframe, text="OK", command=self.ok_command) self.ok_button.pack(side=LEFT) self.filter_button = Button(self.botframe, text="Filter", command=self.filter_command) self.filter_button.pack(side=LEFT, expand=YES) self.cancel_button = Button(self.botframe, text="Cancel", command=self.cancel_command) self.cancel_button.pack(side=RIGHT) self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) # XXX Are the following okay for a general audience? self.top.bind('<Alt-w>', self.cancel_command) self.top.bind('<Alt-W>', self.cancel_command) def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): if key and key in dialogstates: self.directory, pattern = dialogstates[key] else: dir_or_file = os.path.expanduser(dir_or_file) if os.path.isdir(dir_or_file): self.directory = dir_or_file else: self.directory, default = os.path.split(dir_or_file) self.set_filter(self.directory, pattern) self.set_selection(default) self.filter_command() self.selection.focus_set() self.top.wait_visibility() # window needs to be visible for the grab self.top.grab_set() self.how = None self.master.mainloop() # Exited by self.quit(how) if key: directory, pattern = self.get_filter() if self.how: directory = os.path.dirname(self.how) dialogstates[key] = directory, pattern self.top.destroy() return self.how def quit(self, how=None): self.how = how self.master.quit() # Exit mainloop() def dirs_double_event(self, event): self.filter_command() def dirs_select_event(self, event): dir, pat = self.get_filter() subdir = self.dirs.get('active') dir = os.path.normpath(os.path.join(self.directory, subdir)) self.set_filter(dir, pat) def files_double_event(self, event): self.ok_command() def files_select_event(self, event): file = self.files.get('active') self.set_selection(file) def ok_event(self, event): self.ok_command() def ok_command(self): self.quit(self.get_selection()) def filter_command(self, event=None): dir, pat = self.get_filter() try: names = os.listdir(dir) except OSError: self.master.bell() return self.directory = dir self.set_filter(dir, pat) names.sort() subdirs = [os.pardir] matchingfiles = [] for name in names: fullname = os.path.join(dir, name) if os.path.isdir(fullname): subdirs.append(name) elif fnmatch.fnmatch(name, pat): matchingfiles.append(name) self.dirs.delete(0, END) for name in subdirs: self.dirs.insert(END, name) self.files.delete(0, END) for name in matchingfiles: self.files.insert(END, name) head, tail = os.path.split(self.get_selection()) if tail == os.curdir: tail = '' self.set_selection(tail) def get_filter(self): filter = self.filter.get() filter = os.path.expanduser(filter) if filter[-1:] == os.sep or os.path.isdir(filter): filter = os.path.join(filter, "*") return os.path.split(filter) def get_selection(self): file = self.selection.get() file = os.path.expanduser(file) return file def cancel_command(self, event=None): self.quit() def set_filter(self, dir, pat): if not os.path.isabs(dir): try: pwd = os.getcwd() except OSError: pwd = None if pwd: dir = os.path.join(pwd, dir) dir = os.path.normpath(dir) self.filter.delete(0, END) self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) def set_selection(self, file): self.selection.delete(0, END) self.selection.insert(END, os.path.join(self.directory, file))
def createWindow(): w = Toplevel() w.title("新建窗口") # 绑定右键事件,在窗口的任意位置都可以右键弹出菜单 w.bind("<ButtonPress-2>", popup)
class LoginDialog: def __init__(self, host): self.__interna_init() self.__host = host self.__initialized = False if TKTk is not None: self.__create_content() self.__initialized = True def __interna_init(self): self.__rootFrame = None self.__top = None self.__usrEntry = None self.__pwdEntry = None self.__accepted = False self.__host = None self.__usr = None self.__pwd = None def __cancel_action(self): self.__accepted = False self.__rootFrame.destroy() def __login_action(self): self.__accepted = True self.__usr = self.__usrEntry.get() self.__pwd = self.__pwdEntry.get() self.__rootFrame.destroy() def __enter_action(self, event): self.__login_action() def __create_content(self): self.__rootFrame = TKTk() self.__rootFrame.withdraw() self.__top = TKToplevel(self.__rootFrame) self.__top.title("Login") self.__top.protocol("WM_DELETE_WINDOW", self.__rootFrame.destroy) self.__top.bind('<Return>', self.__enter_action) self.__top.update_idletasks() width = self.__top.winfo_width() height = self.__top.winfo_height() x = (self.__top.winfo_screenwidth() // 2) - (width // 2) y = (self.__top.winfo_screenheight() // 2) - (height // 2) self.__top.geometry(f"+{x}+{y}") row = 0 expLabel = TKLabel(self.__top, text='Login to host:') expLabel.grid(row=row, column=0, columnspan=4, padx=5, pady=2) row = row+1 urlLabel = TKLabel(self.__top, text=self.__host) urlLabel.grid(row=row, column=0, columnspan=4, padx=5, pady=2) row = row+1 usrLabel = TKLabel(self.__top, text='User') usrLabel.grid(row=row, column=0, columnspan=2, padx=20, pady=5) self.__usrEntry = TKEntry(self.__top, width=20) self.__usrEntry.grid(row=row, column=2, columnspan=2, padx=5, pady=5) row = row+1 pwdLabel = TKLabel(self.__top, text='Password') pwdLabel.grid(row=row, column=0, columnspan=2, padx=20, pady=5) self.__pwdEntry = TKEntry(self.__top, width=20, show="*") self.__pwdEntry.grid(row=row, column=2, columnspan=2, padx=5, pady=5) row = row+1 cancelButton = TKButton(self.__top, text='Cancel', command=self.__cancel_action) cancelButton.grid(row=row, column=1, padx=5, pady=5) loginButton = TKButton(self.__top, text='Login', command=self.__login_action) loginButton.grid(row=row, column=2, padx=5, pady=5) def show_login(self): if self.__initialized: self.__usrEntry.focus_set() self.__rootFrame.mainloop() else: print("tkinter python module is not available.\n\ Please, install tkinter module or use command line login utility.") def is_accepted(self): return self.__accepted def get_user(self): return self.__usr def get_password(self): return self.__pwd
def norm_grabber(): check_norm.set( 'Coor' ) #This forces equation to set as default in case user doesn't choose two points if plot_done.get() or load_var.get() != '': try: for t in spectrum.texts: t.set_visible( False) #Removes x marks to prepare for new offset spectrum.grid(b=True, which='both', axis='both') f.canvas.draw() def onclick(event): ix, iy = float(event.xdata), float(event.ydata) spectrum.text(ix, iy, 'x', ha='center', va='center') f.canvas.draw() global coords coords.append((ix, iy)) param_norm_x.set(coords[0][0]) param_norm_y.set(coords[0][1]) f.canvas.mpl_disconnect(cid) spectrum.grid(b=False) spectrum.grid(False, which='minor') f.canvas.draw() for t in spectrum.texts: t.set_visible(False) coords = [] ask_plot() cid = f.canvas.mpl_connect('button_press_event', onclick) except Exception as ex: print( 'Exception thrown whilst obtaining/applying normalization.' + ex) messagebox.showerror( 'Error', 'Something went wrong with the normaliz' + 'ation.') else: #If no plot or exp data, it opens a window for input fields = ['x', 'y'] defaults = [3104.161, 6.213744] def quit_window(): root.destroy() def fetch(entries): val = [] for entry in entries: try: val.append(float(entry.get())) except: messagebox.showerror( 'Invalid parameter', 'One input is not a num' + 'ber. Parameters will reset.') redo_form(entries) param_norm_x.set(val[0]) param_norm_y.set(val[1]) ask_plot() def make_form(root, fields): entries = [] row = Frame(root) lab = Label(row, width=40, text='With no plot, choose coordinates to ' + 'normalize.', anchor='w') row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) row = Frame(root) lab = Label(row, width=5, text=fields[0], anchor='w') ent = Entry(row) ent.insert(0, defaults[0]) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append(ent) row = Frame(root) lab = Label(row, width=5, text=fields[1], anchor='w') ent = Entry(row) ent.insert(0, defaults[1]) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append(ent) return entries def redo_form(entries): i = 0 for entry in entries: entry.delete(0, END) entry.insert(0, defaults[i]) i += 1 fetch(entries) #Normalizer submain #------------------------------------------------------------------------ root = Toplevel() root.title('Normalizer point') #root.iconbitmap(r'favico.ico') ents = make_form(root, fields) b1 = ttk.Button(root, text='Save', command=(lambda e=ents: fetch(e))) b1.pack(side=LEFT, padx=5, pady=5) root.bind('<Return>', lambda events, e=ents: fetch(e) ) #If presses enter, it saves ('presses' b1 button) b2 = ttk.Button(root, text='Reset', command=(lambda e=ents: redo_form(e))) b2.pack(side=LEFT, padx=5, pady=5) b3 = ttk.Button(root, text='Quit', command=quit_window) b3.pack(side=LEFT, padx=5, pady=5)
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 tkinter.filedialog from tkinter import END openfile = tkinter.filedialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END,line) def SaveCommand(self): import tkinter.filedialog from tkinter import END saveasfile = tkinter.filedialog.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 tkinter.filedialog outputfilename = tkinter.filedialog.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 # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior physicallines = [str(line) for line in 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: from vmtk import vmtkscripts from vmtk import pypes 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: module = importlib.import_module('vmtk.'+moduleName) # Find the principle class to instantiate the requested action defined inside the requested writerModule script. # Returns a single member list (containing the principle class name) which satisfies the following criteria: # 1) is a class defined within the script # 2) the class is a subclass of pypes.pypescript scriptObjectClasses = [x for x in dir(module) if isclass(getattr(module, x)) and issubclass(getattr(module, x), pypes.pypeScript)] scriptObjectClassName = scriptObjectClasses[0] scriptObject = getattr(module, scriptObjectClassName) scriptObject = scriptObject() members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-'+member.OptionName) list = [option for option in optionlist if option.count(word)] except: return list else: list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word)] for index, item in enumerate(list): # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user. if 'vmtk.' == item[0:5]: splitList = item.split('.') list[index] = splitList[1] else: continue 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 tkinter.filedialog openfilename = tkinter.filedialog.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: module = importlib.import_module('vmtk.'+modulename) except ImportError: return None scriptnames = [scriptname for scriptname in getattr(module, '__all__')] for index, scriptname in enumerate(scriptnames): # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user. if 'vmtk.' == scriptname[0:5]: splitList = scriptname.split('.') scriptnames[index] = splitList[1] else: continue 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 plot_parameters(): def quit_window(): root.destroy() fields = ('Voigt fraction', 'Gaussian width', 'Lorentzian width', 'Energy axis step', 'Energy offset', 'Min. Energy', 'Max. Energy', 'Maxwellian dist.', 'Background noise', 'Normalization') defaults = asarray( [.56, .62, .19, .01, 0, 3087.94, 3118.73, .99, .7, 3104.161]) def fetch(entries): val = [] for entry in entries: try: val.append(float(entry.get())) except: messagebox.showerror( 'Invalid parameter', 'One input is not a numbe' + 'r. Parameters will reset.') redo_form(entries) param_changed.set(True) if val[0] >= 0 and val[0] <= 1: param_voigt.set(val[0]) else: messagebox.showwarning( 'Invalid parameter.', 'Voigt fraction must be ' + 'between 0 and 1. 1 being a fully Gaussian dis' + 'tribution and 0 a fully Lorentzian one. Value' + ' was not changed.') if val[1] >= 0: param_gauss.set(val[1]) else: messagebox.showwarning( 'Invalid parameter.', 'Gaussian width must be ' + 'greater than 0. Value was not changed.') if val[2] >= 0: param_loren.set(val[2]) else: messagebox.showwarning( 'Invalid parameter.', 'Lorentzian width must b' + 'e greater than 0. Value was not changed.') if val[3] > 0: param_step.set(val[3]) else: messagebox.showwarning( 'Invalid parameter.', 'Step must be greater th' + 'an 0. Value was not changed.') param_hwoff.set(val[4]) if val[5] < val[6]: param_min.set(val[5]) param_max.set(val[6]) else: messagebox.showwarning( 'Invalid parameters.', 'The energy interval is' + ' not valid. The minimum value is greater than' + ' the maximum value. Values were not changed.') if val[7] >= 0 and val[7] <= 1: param_mw.set(val[7]) else: messagebox.showwarning( 'Invalid parameter.', 'The Maxwellian vs. non-' + 'Maxwellian distribution fraction must be betw' + 'een 0 and 1. 1 being a fully Maxwellian distr' + 'ibution and 0 a fully non-Maxwellian one. Val' + 'ue was not changed.') if check_off.get() == 'Set': param_m.set(0) param_b.set(ent_off.get()) if check_norm.get() == 'Data': param_norm_x.set(ent_norm.get()) ask_plot() def off_set(): if check_off.get() == 'Set': ent_off.configure(state='normal') param_m.set(0) param_b.set(ent_off.get()) ask_plot() elif check_off.get() == 'Chi': if load_var.get() == '': messagebox.showwarning( 'Warning: No data', 'Missing data to plot wi' + 'th offset chi2 minimization.') check_off.set('Set') off_set() else: ent_off.configure(state='disabled') ask_plot() else: #Else two point ent_off.configure(state='disabled') off_two_grabber() def norm(): if check_norm.get() == 'None': ent_norm.configure(state='disabled') ask_plot() elif check_norm.get() == 'Data': if load_var.get() == '': messagebox.showwarning( 'Warning: No data', 'Missing data plot to no' + 'rmalize from.') check_norm.set('None') norm() else: ent_norm.configure(state='normal') param_norm_x.set(ent_norm.get()) ask_plot() else: #Else coordinate ent_norm.configure(state='disabled') norm_grabber() def make_form(root, fields): entries = [] i = 0 for field in fields[:8]: row = Frame(root) lab = Label(row, width=15, text=field, anchor='w') ent = Entry(row) ent.insert(0, defaults[i]) i += 1 row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append(ent) return entries def redo_form(entries): i = 0 for entry in entries: if i < 8: entry.delete(0, END) entry.insert(0, defaults[i]) i += 1 elif i == 8: ent_off.delete(0, END) ent_off.insert(0, defaults[i]) i += 1 elif i == 9: ent_norm.delete(0, END) ent_norm.insert(0, defaults[i]) fetch(entries) #Parameters main #-------------------------------------------------------------------------- root = Toplevel() root.title('Parameters') #root.iconbitmap(r'favico.ico') ents = make_form(root, fields) row = Frame(root) #For the offset parameter lab = Label(row, width=15, text=fields[8], anchor='w') row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent_off = Entry(row, width=8) ent_off.insert(0, defaults[8]) c1 = ttk.Radiobutton(row, text='Fixed', variable=check_off, value='Set', command=off_set) c2 = ttk.Radiobutton(row, text='Min. \u03c7^2', variable=check_off, value='Chi', command=off_set) c3 = ttk.Radiobutton(row, text='Two points', variable=check_off, value='TwoPoints', command=off_set) c3.pack(side=RIGHT, fill=X) c2.pack(side=RIGHT, fill=X) ent_off.pack(side=RIGHT) c1.pack(side=RIGHT, fill=X) ents.append(ent_off) row = Frame(root) #For the normalization parameter lab = Label(row, width=15, text=fields[9], anchor='w') row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent_norm = Entry(row, width=8) ent_norm.insert(0, defaults[9]) d1 = ttk.Radiobutton(row, text='None', variable=check_norm, value='None', command=norm) d2 = ttk.Radiobutton(row, text='Data point', variable=check_norm, value='Data', command=norm) d3 = ttk.Radiobutton(row, text='Coordinate', variable=check_norm, value='Coor', command=norm) d3.pack(side=RIGHT, fill=X) ent_norm.pack(side=RIGHT) d2.pack(side=RIGHT, fill=X) d1.pack(side=RIGHT, fill=X) ents.append(ent_norm) norm() #So that window checks proper radiobuttons b1 = ttk.Button(root, text='Save', command=(lambda e=ents: fetch(e))) b1.pack(side=LEFT, padx=5, pady=5) root.bind('<Return>', lambda events, e=ents: fetch(e) ) #If presses enter, it saves ('presses' b1 button) b2 = ttk.Button(root, text='Reset', command=(lambda e=ents: redo_form(e))) b2.pack(side=LEFT, padx=5, pady=5) b3 = ttk.Button(root, text='Quit', command=quit_window) b3.pack(side=LEFT, padx=5, pady=5) root.mainloop()
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 tkinter.filedialog from tkinter import END openfile = tkinter.filedialog.askopenfile() if not openfile: return for line in openfile.readlines(): self.text_input.insert(END, line) def SaveCommand(self): import tkinter.filedialog from tkinter import END saveasfile = tkinter.filedialog.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 tkinter.filedialog outputfilename = tkinter.filedialog.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 # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior physicallines = [ str(line) for line in 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: from vmtk import vmtkscripts from vmtk import pypes 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: module = importlib.import_module('vmtk.' + moduleName) # Find the principle class to instantiate the requested action defined inside the requested writerModule script. # Returns a single member list (containing the principle class name) which satisfies the following criteria: # 1) is a class defined within the script # 2) the class is a subclass of pypes.pypescript scriptObjectClasses = [ x for x in dir(module) if isclass(getattr(module, x)) and issubclass(getattr(module, x), pypes.pypeScript) ] scriptObjectClassName = scriptObjectClasses[0] scriptObject = getattr(module, scriptObjectClassName) scriptObject = scriptObject() members = scriptObject.InputMembers + scriptObject.OutputMembers for member in members: optionlist.append('-' + member.OptionName) list = [option for option in optionlist if option.count(word)] except: return list else: list = [ scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ] for index, item in enumerate(list): # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user. if 'vmtk.' == item[0:5]: splitList = item.split('.') list[index] = splitList[1] else: continue 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 tkinter.filedialog openfilename = tkinter.filedialog.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: module = importlib.import_module('vmtk.' + modulename) except ImportError: return None scriptnames = [scriptname for scriptname in getattr(module, '__all__')] for index, scriptname in enumerate(scriptnames): # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user. if 'vmtk.' == scriptname[0:5]: splitList = scriptname.split('.') scriptnames[index] = splitList[1] else: continue 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 CFGEditor(object): """ A dialog window for creating and editing context free grammars. ``CFGEditor`` imposes the following restrictions: - All nonterminals must be strings consisting of word characters. - All terminals must be strings consisting of word characters and space characters. """ # Regular expressions used by _analyze_line. Precompile them, so # we can process the text faster. ARROW = SymbolWidget.SYMBOLS['rightarrow'] _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|("+ARROW+"))") _ARROW_RE = re.compile("\s*(->|("+ARROW+"))\s*") _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" + # LHS "(->|("+ARROW+"))\s*" + # arrow r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$") # RHS _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|("+ARROW+")") _BOLD = ('helvetica', -12, 'bold') def __init__(self, parent, cfg=None, set_cfg_callback=None): self._parent = parent if cfg is not None: self._cfg = cfg else: self._cfg = ContextFreeGrammar(Nonterminal('S'), []) self._set_cfg_callback = set_cfg_callback self._highlight_matching_nonterminals = 1 # Create the top-level window. self._top = Toplevel(parent) self._init_bindings() self._init_startframe() self._startframe.pack(side='top', fill='x', expand=0) self._init_prodframe() self._prodframe.pack(side='top', fill='both', expand=1) self._init_buttons() self._buttonframe.pack(side='bottom', fill='x', expand=0) self._textwidget.focus() def _init_startframe(self): frame = self._startframe = Frame(self._top) self._start = Entry(frame) self._start.pack(side='right') Label(frame, text='Start Symbol:').pack(side='right') Label(frame, text='Productions:').pack(side='left') self._start.insert(0, self._cfg.start().symbol()) def _init_buttons(self): frame = self._buttonframe = Frame(self._top) Button(frame, text='Ok', command=self._ok, underline=0, takefocus=0).pack(side='left') Button(frame, text='Apply', command=self._apply, underline=0, takefocus=0).pack(side='left') Button(frame, text='Reset', command=self._reset, underline=0, takefocus=0,).pack(side='left') Button(frame, text='Cancel', command=self._cancel, underline=0, takefocus=0).pack(side='left') Button(frame, text='Help', command=self._help, underline=0, takefocus=0).pack(side='right') def _init_bindings(self): self._top.title('CFG Editor') self._top.bind('<Control-q>', self._cancel) self._top.bind('<Alt-q>', self._cancel) self._top.bind('<Control-d>', self._cancel) #self._top.bind('<Control-x>', self._cancel) self._top.bind('<Alt-x>', self._cancel) self._top.bind('<Escape>', self._cancel) #self._top.bind('<Control-c>', self._cancel) self._top.bind('<Alt-c>', self._cancel) self._top.bind('<Control-o>', self._ok) self._top.bind('<Alt-o>', self._ok) self._top.bind('<Control-a>', self._apply) self._top.bind('<Alt-a>', self._apply) self._top.bind('<Control-r>', self._reset) self._top.bind('<Alt-r>', self._reset) self._top.bind('<Control-h>', self._help) self._top.bind('<Alt-h>', self._help) self._top.bind('<F1>', self._help) def _init_prodframe(self): self._prodframe = Frame(self._top) # Create the basic Text widget & scrollbar. self._textwidget = Text(self._prodframe, background='#e0e0e0', exportselection=1) self._textscroll = Scrollbar(self._prodframe, takefocus=0, orient='vertical') self._textwidget.config(yscrollcommand = self._textscroll.set) self._textscroll.config(command=self._textwidget.yview) self._textscroll.pack(side='right', fill='y') self._textwidget.pack(expand=1, fill='both', side='left') # Initialize the colorization tags. Each nonterminal gets its # own tag, so they aren't listed here. self._textwidget.tag_config('terminal', foreground='#006000') self._textwidget.tag_config('arrow', font='symbol') self._textwidget.tag_config('error', background='red') # Keep track of what line they're on. We use that to remember # to re-analyze a line whenever they leave it. self._linenum = 0 # Expand "->" to an arrow. self._top.bind('>', self._replace_arrows) # Re-colorize lines when appropriate. self._top.bind('<<Paste>>', self._analyze) self._top.bind('<KeyPress>', self._check_analyze) self._top.bind('<ButtonPress>', self._check_analyze) # Tab cycles focus. (why doesn't this work??) def cycle(e, textwidget=self._textwidget): textwidget.tk_focusNext().focus() self._textwidget.bind('<Tab>', cycle) prod_tuples = [(p.lhs(),[p.rhs()]) for p in self._cfg.productions()] for i in range(len(prod_tuples)-1,0,-1): if (prod_tuples[i][0] == prod_tuples[i-1][0]): if () in prod_tuples[i][1]: continue if () in prod_tuples[i-1][1]: continue print(prod_tuples[i-1][1]) print(prod_tuples[i][1]) prod_tuples[i-1][1].extend(prod_tuples[i][1]) del prod_tuples[i] for lhs, rhss in prod_tuples: print(lhs, rhss) s = '%s ->' % lhs for rhs in rhss: for elt in rhs: if isinstance(elt, Nonterminal): s += ' %s' % elt else: s += ' %r' % elt s += ' |' s = s[:-2] + '\n' self._textwidget.insert('end', s) self._analyze() # # Add the producitons to the text widget, and colorize them. # prod_by_lhs = {} # for prod in self._cfg.productions(): # if len(prod.rhs()) > 0: # prod_by_lhs.setdefault(prod.lhs(),[]).append(prod) # for (lhs, prods) in prod_by_lhs.items(): # self._textwidget.insert('end', '%s ->' % lhs) # self._textwidget.insert('end', self._rhs(prods[0])) # for prod in prods[1:]: # print '\t|'+self._rhs(prod), # self._textwidget.insert('end', '\t|'+self._rhs(prod)) # print # self._textwidget.insert('end', '\n') # for prod in self._cfg.productions(): # if len(prod.rhs()) == 0: # self._textwidget.insert('end', '%s' % prod) # self._analyze() # def _rhs(self, prod): # s = '' # for elt in prod.rhs(): # if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol() # else: s += ' %r' % elt # return s def _clear_tags(self, linenum): """ Remove all tags (except ``arrow`` and ``sel``) from the given line of the text widget used for editing the productions. """ start = '%d.0'%linenum end = '%d.end'%linenum for tag in self._textwidget.tag_names(): if tag not in ('arrow', 'sel'): self._textwidget.tag_remove(tag, start, end) def _check_analyze(self, *e): """ Check if we've moved to a new line. If we have, then remove all colorization from the line we moved to, and re-colorize the line that we moved from. """ linenum = int(self._textwidget.index('insert').split('.')[0]) if linenum != self._linenum: self._clear_tags(linenum) self._analyze_line(self._linenum) self._linenum = linenum def _replace_arrows(self, *e): """ Replace any ``'->'`` text strings with arrows (char \\256, in symbol font). This searches the whole buffer, but is fast enough to be done anytime they press '>'. """ arrow = '1.0' while True: arrow = self._textwidget.search('->', arrow, 'end+1char') if arrow == '': break self._textwidget.delete(arrow, arrow+'+2char') self._textwidget.insert(arrow, self.ARROW, 'arrow') self._textwidget.insert(arrow, '\t') arrow = '1.0' while True: arrow = self._textwidget.search(self.ARROW, arrow+'+1char', 'end+1char') if arrow == '': break self._textwidget.tag_add('arrow', arrow, arrow+'+1char') def _analyze_token(self, match, linenum): """ Given a line number and a regexp match for a token on that line, colorize the token. Note that the regexp match gives us the token's text, start index (on the line), and end index (on the line). """ # What type of token is it? if match.group()[0] in "'\"": tag = 'terminal' elif match.group() in ('->', self.ARROW): tag = 'arrow' else: # If it's a nonterminal, then set up new bindings, so we # can highlight all instances of that nonterminal when we # put the mouse over it. tag = 'nonterminal_'+match.group() if tag not in self._textwidget.tag_names(): self._init_nonterminal_tag(tag) start = '%d.%d' % (linenum, match.start()) end = '%d.%d' % (linenum, match.end()) self._textwidget.tag_add(tag, start, end) def _init_nonterminal_tag(self, tag, foreground='blue'): self._textwidget.tag_config(tag, foreground=foreground, font=CFGEditor._BOLD) if not self._highlight_matching_nonterminals: return def enter(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='#80ff80') def leave(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='') self._textwidget.tag_bind(tag, '<Enter>', enter) self._textwidget.tag_bind(tag, '<Leave>', leave) def _analyze_line(self, linenum): """ Colorize a given line. """ # Get rid of any tags that were previously on the line. self._clear_tags(linenum) # Get the line line's text string. line = self._textwidget.get(repr(linenum)+'.0', repr(linenum)+'.end') # If it's a valid production, then colorize each token. if CFGEditor._PRODUCTION_RE.match(line): # It's valid; Use _TOKEN_RE to tokenize the production, # and call analyze_token on each token. def analyze_token(match, self=self, linenum=linenum): self._analyze_token(match, linenum) return '' CFGEditor._TOKEN_RE.sub(analyze_token, line) elif line.strip() != '': # It's invalid; show the user where the error is. self._mark_error(linenum, line) def _mark_error(self, linenum, line): """ Mark the location of an error in a line. """ arrowmatch = CFGEditor._ARROW_RE.search(line) if not arrowmatch: # If there's no arrow at all, highlight the whole line. start = '%d.0' % linenum end = '%d.end' % linenum elif not CFGEditor._LHS_RE.match(line): # Otherwise, if the LHS is bad, highlight it. start = '%d.0' % linenum end = '%d.%d' % (linenum, arrowmatch.start()) else: # Otherwise, highlight the RHS. start = '%d.%d' % (linenum, arrowmatch.end()) end = '%d.end' % linenum # If we're highlighting 0 chars, highlight the whole line. if self._textwidget.compare(start, '==', end): start = '%d.0' % linenum end = '%d.end' % linenum self._textwidget.tag_add('error', start, end) def _analyze(self, *e): """ Replace ``->`` with arrows, and colorize the entire buffer. """ self._replace_arrows() numlines = int(self._textwidget.index('end').split('.')[0]) for linenum in range(1, numlines+1): # line numbers start at 1. self._analyze_line(linenum) def _parse_productions(self): """ Parse the current contents of the textwidget buffer, to create a list of productions. """ productions = [] # Get the text, normalize it, and split it into lines. text = self._textwidget.get('1.0', 'end') text = re.sub(self.ARROW, '->', text) text = re.sub('\t', ' ', text) lines = text.split('\n') # Convert each line to a CFG production for line in lines: line = line.strip() if line=='': continue productions += parse_cfg_production(line) #if line.strip() == '': continue #if not CFGEditor._PRODUCTION_RE.match(line): # raise ValueError('Bad production string %r' % line) # #(lhs_str, rhs_str) = line.split('->') #lhs = Nonterminal(lhs_str.strip()) #rhs = [] #def parse_token(match, rhs=rhs): # token = match.group() # if token[0] in "'\"": rhs.append(token[1:-1]) # else: rhs.append(Nonterminal(token)) # return '' #CFGEditor._TOKEN_RE.sub(parse_token, rhs_str) # #productions.append(Production(lhs, *rhs)) return productions def _destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def _ok(self, *e): self._apply() self._destroy() def _apply(self, *e): productions = self._parse_productions() start = Nonterminal(self._start.get()) cfg = ContextFreeGrammar(start, productions) if self._set_cfg_callback is not None: self._set_cfg_callback(cfg) def _reset(self, *e): self._textwidget.delete('1.0', 'end') for production in self._cfg.productions(): self._textwidget.insert('end', '%s\n' % production) self._analyze() if self._set_cfg_callback is not None: self._set_cfg_callback(self._cfg) def _cancel(self, *e): try: self._reset() except: pass self._destroy() def _help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75, font='fixed') except: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75)
# add figure canvas = Canvas(figure, root) canvas.mpl_connect('motion_notify_event', axes_moved) canvas.get_tk_widget().place(x=150, y=0, width=WIDTH - 150, height=HEIGHT) # handle child resize def child_resize(event): child_canvas.get_tk_widget().place(x=0, y=0, width=child.winfo_width(), height=child.winfo_height()) # child tk for show window child = Toplevel(root) child.protocol('WM_DELETE_WINDOW', lambda: child.withdraw()) child.bind('<Configure>', child_resize) child.withdraw() # child figure child_figure = Figure() child_graph_1 = child_figure.add_subplot(211) child_plot_1 = None child_figure.tight_layout() child_graph_2 = child_figure.add_subplot(212) child_plot_2 = None child_v_line_2 = None child_left_line_2 = None child_right_line_2 = None child_scatter_2 = None
class SpeciesListDialog: def __init__(self, parent): self.parent = parent self.gui = Toplevel(parent.guiRoot) self.gui.grab_set() self.gui.focus() self.gui.columnconfigure(0, weight=1) self.gui.rowconfigure(1, weight=1) Label(self.gui, text="Registered Species:").grid(row=0, column=0, pady=5, padx=5, sticky="w") self.listRegisteredSpecies = Listbox(self.gui, width=70) self.buttonAdd = Button(self.gui, text=" + ") self.buttonDel = Button(self.gui, text=" - ") self.listRegisteredSpecies.grid(row=1, column=0, columnspan=3, sticky="nswe", pady=5, padx=5) self.buttonAdd.grid(row=2, column=1, pady=5, padx=5) self.buttonDel.grid(row=2, column=2, pady=5, padx=5) # Set (minimum + max) Window size self.gui.update() self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height()) # self.gui.maxsize(self.gui.winfo_width(), self.gui.winfo_height()) self.actionUpdate(None) self.gui.bind("<<Update>>", self.actionUpdate) self.gui.protocol("WM_DELETE_WINDOW", self.actionClose) self.buttonDel.bind("<ButtonRelease>", self.actionDel) self.buttonAdd.bind("<ButtonRelease>", self.actionAdd) self.gui.mainloop() def actionClose(self): self.parent.guiRoot.event_generate("<<Update>>", when="tail") self.gui.destroy() def actionUpdate(self, event): self.listRegisteredSpecies.delete(0, "end") for (taxid, name) in self.parent.optimizer.speciesList: self.listRegisteredSpecies.insert("end", taxid + ": " + name) def actionDel(self, event): try: selection = self.listRegisteredSpecies.selection_get() selectionSplit = selection.split(": ") self.parent.optimizer.speciesList.remove((selectionSplit[0], selectionSplit[1])) self.gui.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionAdd(self, Event): SpeciesSearchDialog(self.parent, self)
class TkTimerCore(TimerCore): def __init__(self, *args, title, font_size, **kwargs): def close_handler(event): self.close() def clicked_handler(event): self.interact() self.master = Tk() self.master.wm_title(title) self.master.bind('<Destroy>', close_handler) self.label = Label(self.master, font='Sans {}'.format(int(font_size))) self.label.pack(expand=True) self.control = Toplevel() self.control.wm_title(title + ' (control)') self.control.minsize(150, 150) self.control.bind('<Destroy>', close_handler) self.button = Button(self.control, text='Start/Pause') self.button.bind('<ButtonRelease>', clicked_handler) self.button.pack(expand=True) self.timeout_running = False super().__init__(*args, **kwargs) def start_timeout(self): assert self.timeout_running is False def timeout_call(): if self.timeout_running: self.update() self.master.after(25, timeout_call) self.timeout_running = True timeout_call() def stop_timeout(self): assert self.timeout_running is True self.timeout_running = False def mainloop(self): return self.master.mainloop() def shutdown(self): self.master.quit() def set_label_text(self, text, finished=False): self.label.config(text=text) if finished: self.label.config(fg='red')