def draw_automata(turing_machine=None): w = len(turing_machine.states) h = len(turing_machine.rules) root = Tk() frame = Frame(root, width=800, height=600) frame.grid(row=0, column=0) canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600, scrollregion=(0, -h * 15, w * 100, h * 15*3)) hbar = Scrollbar(frame, orient=HORIZONTAL) hbar.pack(side=BOTTOM, fill=X) hbar.config(command=canvas.xview) vbar = Scrollbar(frame, orient=VERTICAL) vbar.pack(side=RIGHT, fill=Y) vbar.config(command=canvas.yview) canvas.config(width=800, height=600) canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set) canvas.pack(side=LEFT, expand=True, fill=BOTH) for position, state in enumerate(turing_machine.states): state_position[state] = position loop_occurrences[position] = 0 canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw") canvas.itemconfig(canvas_id, text="state-") canvas.insert(canvas_id, 12, "%d" % state) counter = 1 for rule in turing_machine.rules: counter = draw_arrow(state_position[rule.current_state], state_position[rule.next_state], canvas, counter, rule) root.mainloop()
def show_source_tree(head): root = Tk() frame = Frame(root) frame.pack(fill = 'both') tree = tkinter.ttk.Treeview(frame) #insert root subroutine # @type head Node parent_id = tree.insert('', 'end', '', text = head.name) for child in head.children: child.insert_to_tree(tree, parent_id) #add scrollbar v_scrollbar = Scrollbar(frame, orient = VERTICAL, command = tree.yview) h_scrollbar = Scrollbar(frame, orient = HORIZONTAL, command = tree.xview) tree.configure(yscrollcommand = v_scrollbar.set, xscrollcommand = h_scrollbar.set) v_scrollbar.pack(side = 'right', fill = 'y') h_scrollbar.pack(side = 'bottom', fill = 'x') tree.pack(fill = 'both') root.geometry("600x600") root.mainloop()
def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill="both", side="left", padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text="Available Expansions") self._prodlist_label.pack() self._prodlist = Listbox( self._prodframe, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._prodlist.pack(side="right", fill="both", expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert("end", (" %s" % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient="vertical") self._prodlist.config(yscrollcommand=listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side="left", fill="y") # If they select a production, apply it. self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)
class ScrolledText2(Text): def __init__(self, master=None, change_hook=None, **kw): self.frame = Frame(master) self.vbar = Scrollbar(self.frame) self.vbar.pack(side=RIGHT, fill=Y) self.change_hook = change_hook self.hbar = Scrollbar(self.frame, orient=HORIZONTAL) self.hbar.pack(side=BOTTOM,fill=X) kw.update({'yscrollcommand': self.vbar.set}) kw.update({'xscrollcommand': self.hbar.set}) kw.update({'wrap': 'none'}) Text.__init__(self, self.frame, **kw) self.pack(side=LEFT, fill=BOTH, expand=True) self.vbar['command'] = self.yview self.hbar['command'] = self.xview # Copy geometry methods of self.frame without overriding Text # methods -- hack! text_meths = list(vars(Text).keys()) methods = list(vars(Pack).keys()) + list(vars(Grid).keys()) + list(vars(Place).keys()) methods = set(methods).difference(text_meths) for m in methods: if m[0] != '_' and m != 'config' and m != 'configure': setattr(self, m, getattr(self.frame, m)) def __str__(self): return str(self.frame)
def _init_results_box(self, parent): innerframe = Frame(parent) i1 = Frame(innerframe) i2 = Frame(innerframe) vscrollbar = Scrollbar(i1, borderwidth=1) hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz") self.results_box = Text( i1, font=tkinter.font.Font(family="courier", size="16"), state="disabled", borderwidth=1, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set, wrap="none", width="40", height="20", exportselection=1, ) self.results_box.pack(side="left", fill="both", expand=True) self.results_box.tag_config(self._HIGHLIGHT_WORD_TAG, foreground=self._HIGHLIGHT_WORD_COLOUR) self.results_box.tag_config(self._HIGHLIGHT_LABEL_TAG, foreground=self._HIGHLIGHT_LABEL_COLOUR) vscrollbar.pack(side="left", fill="y", anchor="e") vscrollbar.config(command=self.results_box.yview) hscrollbar.pack(side="left", fill="x", expand=True, anchor="w") hscrollbar.config(command=self.results_box.xview) # there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!! Label(i2, text=" ", background=self._BACKGROUND_COLOUR).pack(side="left", anchor="e") i1.pack(side="top", fill="both", expand=True, anchor="n") i2.pack(side="bottom", fill="x", anchor="s") innerframe.pack(side="top", fill="both", expand=True)
def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Expansions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand = listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)
def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill='both', side='left', padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text='Examples') self._exampleList_label.pack() self._exampleList = Listbox(self._exampleFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._exampleList.pack(side='right', fill='both', expand=1) for example in self._examples: self._exampleList.insert('end', (' %s' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient='vertical') self._exampleList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side='left', fill='y') # If they select a example, apply it. self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select)
def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill="both", side="left", padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text="Examples") self._exampleList_label.pack() self._exampleList = Listbox( self._exampleFrame, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._exampleList.pack(side="right", fill="both", expand=1) for example in self._examples: self._exampleList.insert("end", (" %s" % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient="vertical") self._exampleList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side="left", fill="y") # If they select a example, apply it. self._exampleList.bind("<<ListboxSelect>>", self._exampleList_select)
def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill="both", side="left", padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text="Readings") self._readingList_label.pack() self._readingList = Listbox( self._readingFrame, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._readingList.pack(side="right", fill="both", expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient="vertical") self._readingList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side="right", fill="y") self._populate_readingListbox()
def __init__(self, parent, list_model_factory, label_text): Frame.__init__(self, parent) scrollbar = Scrollbar(self, orient=VERTICAL) Label(self, text=label_text).pack() self.check_list_box = ProgressListBox(self, scrollbar, list_model_factory) scrollbar.config(command=self.check_list_box.yview) scrollbar.pack(side=RIGHT, fill=Y) self.check_list_box.pack(side=LEFT, fill=BOTH, expand=1)
def __init__(self, *, multiple_runner_class, input_spec, left_name, right_name): """Sets up windows and the instance of RunMultipleTimes that will do the actual work.""" #: The input_spec is an iterable of #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`. self.input_spec = input_spec #: Class responsible for the actual running multiple times. self.multiple_runner_class = multiple_runner_class #: Main window self.mw = mw = Tk() #: Statistics thus far, grouped by input. self.stats = AllStats(left_name=left_name, right_name=right_name) #: Are we in the process of quitting? self.quitting = False self.status_label = Label( mw, text='Not Started', font=('Times', 20), foreground='#000000') self.status_label_text = self.status_label.cget('text') self.status_label.pack(side=TOP, expand=True, fill=X) #: Has a run started? Used to ensure single run. self.run_started = False details_frame = Frame(mw) details_frame.pack(side=TOP) #: listbox on left listing inputs. frame = Frame(details_frame) scrollbar = Scrollbar(frame, orient=VERTICAL) listbox = Listbox( frame, yscrollcommand=scrollbar.set, height=25, width=70, selectmode=SINGLE) scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=1) listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+') frame.pack(side=LEFT) self.listbox = listbox #: Canvas on right for details self.canvas = Canvas( details_frame, width=kCanvasWidth, height=kCanvasHeight, background='#FFFFFF') self.canvas.pack(side=LEFT) #: which input are we displaying the details of? self.display_details_for = None #: Thread used for running self.thread = None self.mw.bind('<KeyPress-q>', lambda e: self.Quit()) self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun()) self.Refresher() self.mw.after(1000, self.KickOffRun)
def textWindOn(): from tkinter import Scrollbar global w, text, buttons global scroll2 try: scroll2.destroy() except: pass scroll2 = Scrollbar(w, orient='horizontal', command=text.xview) scroll2.pack(after=buttons, side='bottom', fill='x') text.configure(xscrollcommand=scroll2.set, wrap='none')
def editorText(self): self.text_edit = Text(self.root, borderwidth=3, relief="sunken") self.text_edit.config(font=("consolas", 12), undo=True, wrap='word') self.text_edit.pack(side=BOTTOM) # create a Scrollbar and associate it with txt scrollb = Scrollbar(self.text_edit, command=self.text_edit.yview) self.text_edit['yscrollcommand'] = scrollb.set self.text_edit.pack(side=BOTTOM,fill=BOTH, expand=True) scrollb.pack(side=RIGHT, fill=Y, expand=False)
def __init__(self, tk: Tk): tk.title("Layered Polygons") menubar = Menu(tk) menu_file = Menu(menubar, tearoff=0) menu_file.add_command(label="New...", command=self._new_scene) menu_file.add_command(label="Open...", command=self._open_scene) menu_file.add_separator() menu_file.add_command(label="Save", command=self._save_scene) menu_file.add_command(label="Save As...", command=self._save_scene_as) menu_file.add_separator() menu_export = Menu(menu_file, tearoff=0) menu_export.add_command(label="Wavefront (.obj)...", command=self._export_obj) menu_file.add_cascade(label="Export As", menu=menu_export) menu_file.add_separator() menu_file.add_command(label="Quit", command=self._quit_app) menubar.add_cascade(label="File", menu=menu_file) tk.config(menu=menubar) paned = PanedWindow(tk, relief=RAISED) paned.pack(fill=BOTH, expand=1) frame = Frame(paned) paned.add(frame) self._canvas = LayPolyCanvas(frame) bar_x = Scrollbar(frame, orient=HORIZONTAL) bar_x.pack(side=BOTTOM, fill=X) bar_x.config(command=self._canvas.xview) bar_y = Scrollbar(frame, orient=VERTICAL) bar_y.pack(side=RIGHT, fill=Y) bar_y.config(command=self._canvas.yview) self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set) self._canvas.pack(side=LEFT, expand=True, fill=BOTH) # Thanks to the two guys on Stack Overflow for that! # ( http://stackoverflow.com/a/7734187 ) self._layer_list = Listbox(paned, selectmode=SINGLE) paned.add(self._layer_list) self._scene = None self._current_layer = None self._is_drawing_polygon = False self._tk = tk self._canvas.bind("<Button-1>", self._canvas_left_click) self._canvas.bind("<Button-3>", self._canvas_right_click) self._canvas.bind("<Motion>", self._canvas_mouse_moved) self._layer_list.bind("<<ListboxSelect>>", self._layer_change) self._current_path = None
def textMakePeer(parent): n = 1 while 'peer%i'%n in globals() and globals()['peer%i'%n].winfo_exists(): n += 1 w = globals()['peer%i'%n] = Toplevel() w.wm_title('Text Peer #%i' % n) f = Frame(w, highlightthickness=1, borderwidth=1, relief='sunken') t = create_peer(parent, f, 'text', borderwidth=0, highlightthickness=0) t.pack(expand='yes', fill='both') scroll = Scrollbar(w, command=t.yview) t['yscrollcommand'] = scroll.set scroll.pack(side='right', fill='y') f.pack(expand='yes', fill='both')
def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) self._canvas = canvas canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) if interior.winfo_reqheight() != canvas.winfo_height(): # update the canvas's height to fit the inner frame canvas.config(height=interior.winfo_reqheight()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): """ This function is called when the canvas is configured, that is on resize and so on, """ if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) if interior.winfo_reqheight() != canvas.winfo_height(): # update the inner frame's height to fill the canvas canvas.itemconfigure(interior_id, height=canvas.winfo_height()) canvas.bind('<Configure>', _configure_canvas) return
class TextExtension(Frame): """Extends Frame. Intended as a container for a Text field. Better related data handling and has Y scrollbar.""" def __init__(self, master, textvariable=None, *args, **kwargs): super(TextExtension, self).__init__(master) # Init GUI self._y_scrollbar = Scrollbar(self, orient=VERTICAL) self._text_widget = Text(self, yscrollcommand=self._y_scrollbar.set, *args, **kwargs) self._text_widget.pack(side=LEFT, fill=BOTH, expand=1) self._y_scrollbar.config(command=self._text_widget.yview) self._y_scrollbar.pack(side=RIGHT, fill=Y) if textvariable is not None: if not (isinstance(textvariable, Variable)): raise TypeError("tkinter.Variable type expected, " + str(type(textvariable)) + " given.".format(type(textvariable))) self._text_variable = textvariable self.var_modified() self._text_trace = self._text_widget.bind('<<Modified>>', self.text_modified) self._var_trace = textvariable.trace("w", self.var_modified) def text_modified(self, *args): if self._text_variable is not None: self._text_variable.trace_vdelete("w", self._var_trace) self._text_variable.set(self._text_widget.get(1.0, END)) self._var_trace = self._text_variable.trace("w", self.var_modified) self._text_widget.edit_modified(False) def var_modified(self, *args): self.set_text(self._text_variable.get()) self._text_widget.edit_modified(False) def unhook(self): if self._text_variable is not None: self._text_variable.trace_vdelete("w", self._var_trace) def clear(self): self._text_widget.delete(1.0, END) def set_text(self, _value): self.clear() if (_value is not None): self._text_widget.insert(END, _value)
def __init__(self, master=None,**args): Frame.__init__(self, master,**args) scrollbar = Scrollbar(self, orient=VERTICAL) #нужен для отображения длинных списков scrollbar.unbind("<Key-Up>") scrollbar.unbind("<Key-Down>") scrollbar.unbind("<Key-Left>") scrollbar.unbind("<Key-Right>") scrollbar.pack(side=RIGHT, fill=Y) self.lst = Listbox(self, yscrollcommand=scrollbar.set, bg="grey", selectmode=SINGLE) self.lst.insert(END,"Hide All") self.lst.insert(END,"Show All") self.lst.select_set(0) self.lst.pack(side=LEFT, fill=BOTH, expand=1) scrollbar.config(command=self.lst.yview)
def __init__(self, parent, list_model, label_text): Frame.__init__(self, parent) self._list_model = list_model self._list_objects = [] self._selected_items = [] scrollbar = Scrollbar(self, orient=VERTICAL) Label(self, text=label_text).pack() self.listbox = Listbox(self, selectmode=EXTENDED, exportselection=0, yscrollcommand=scrollbar.set, borderwidth=0, highlightthickness=0) scrollbar.config(command=self.listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) self.listbox.pack(side=LEFT, fill=BOTH, expand=1) self.listbox.bind('<<ListboxSelect>>', self._on_select) self._list_model.list_items_model.add_listener(self._list_items_changed) self._list_model.selected_items_model.add_listener(self._selected_items_changed) self._update_list_items()
def __init__(self, master, valves): Frame.__init__(self, master) scrollbar = Scrollbar(self) scrollbar.pack(side='right', fill='y') scrollbar.config(background='red', activebackground='DarkRed', width=40) text = Text(self, wrap='word', yscrollcommand=scrollbar.set, width=52, height=14, padx=10) text.config(font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4') text.pack() index = 1 for each in valves: text.insert('end', 'VALVE ' + str(index) + '\n\n') text.insert('end', each) text.insert('end', '-------------------------------------------------------\n') index += 1 scrollbar.config(command=text.yview)
class ScrolledText(Text): """Modified version of tkinter.scrolledtext width horizontal scrollbar""" def __init__(self, master=None, **kw): self.frame = Frame(master) self.vbar = Scrollbar(self.frame) self.vbar.pack(side=RIGHT, fill=Y) #>>>MNC: For horizontal scrollbar try: self.hbar = None if kw['wrap'] == NONE: self.hbar = Scrollbar(self.frame, orient=HORIZONTAL) self.hbar.pack(side=BOTTOM, fill=X) kw.update({'xscrollcommand': self.hbar.set}) except KeyError: self.hbar = None #<<<MNC kw.update({'yscrollcommand': self.vbar.set}) Text.__init__(self, self.frame, **kw) self.pack(side=LEFT, fill=BOTH, expand=True) self.vbar['command'] = self.yview #>>>MNC: For horizontal scrollbar if self.hbar is not None: self.hbar['command'] = self.xview #<<<MNC # Copy geometry methods of self.frame without overriding Text # methods -- hack! text_meths = vars(Text).keys() methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys() methods = methods.difference(text_meths) for m in methods: if m[0] != '_' and m != 'config' and m != 'configure': setattr(self, m, getattr(self.frame, m)) def __str__(self): return str(self.frame) def setText(self, text): self.delete(1.0, END) self.insert(END, text) def getText(self): return self.get(1.0, END)
def editor(text): def callback(*args): nonlocal text text = text1.get('1.0', 'end') root.destroy() root = Tk() root.title("Editor") root.geometry("400x500") text1=Text(root,height=25,width=30,font='Arial 12') text1.pack(side='left') text1.insert("1.0",text) scrollbar = Scrollbar(root) scrollbar.pack(side='right') scrollbar['command'] = text1.yview text1['yscrollcommand'] = scrollbar.set button = Tk_button(root, text="Change", width=30, command=callback) button.pack(side='top') root.mainloop() return text
class ScrolledText(Text): def __init__(self, master=None, **kw): self.frame = Frame(master) self.vbar = Scrollbar(self.frame) self.vbar.pack(side=RIGHT, fill=Y) kw.update({'yscrollcommand': self.vbar.set}) Text.__init__(self, self.frame, **kw) self.pack(side=LEFT, fill=BOTH, expand=True) self.vbar['command'] = self.yview # Copy geometry methods of self.frame -- hack! methods = vars(Pack).keys() + vars(Grid).keys() + vars(Place).keys() for m in methods: if m[0] != '_' and m != 'config' and m != 'configure': setattr(self, m, getattr(self.frame, m)) def __str__(self): return str(self.frame)
def _init_results_box(self, parent): innerframe = Frame(parent) i1 = Frame(innerframe) i2 = Frame(innerframe) vscrollbar = Scrollbar(i1, borderwidth=1) hscrollbar = Scrollbar(i2, borderwidth=1, orient='horiz') self.results_box = Text(i1, font=tkinter.font.Font(family='courier', size='16'), state='disabled', borderwidth=1, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set, wrap='none', width='40', height = '20', exportselection=1) self.results_box.pack(side='left', fill='both', expand=True) vscrollbar.pack(side='left', fill='y', anchor='e') vscrollbar.config(command=self.results_box.yview) hscrollbar.pack(side='left', fill='x', expand=True, anchor='w') hscrollbar.config(command=self.results_box.xview) #there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!! Label(i2, text=' ', background=self._BACKGROUND_COLOUR).pack(side='left', anchor='e') i1.pack(side='top', fill='both', expand=True, anchor='n') i2.pack(side='bottom', fill='x', anchor='s') innerframe.pack(side='top', fill='both', expand=True)
def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill='both', side='left', padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text='Readings') self._readingList_label.pack() self._readingList = Listbox(self._readingFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._readingList.pack(side='right', fill='both', expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient='vertical') self._readingList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side='right', fill='y') self._populate_readingListbox()
def __init__(self): self.action = None self.root = root = Tk() root.title('Never gonna fold you up') root.protocol("WM_DELETE_WINDOW", self.close) root.pack_propagate(True) scrollbar = Scrollbar(root, orient=tkinter.VERTICAL) self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set) self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) scrollbar.config(command=self.problem_list.yview) scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y) self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas()) self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500) self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT) self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas()) button_frame = Frame(root) button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT) # Reposition the figure so it's center of mass is at 0.5, 0.5 v = IntVar() self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas()) self.center_cb.var = v self.center_cb.pack(side=tkinter.TOP) # Use meshes.reconstruct_facets instead of polygon/hole logic. v = IntVar() self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas()) self.reconstruct_cb.var = v self.reconstruct_cb.pack(side=tkinter.TOP) self.populate_problems() self.current_problem_name = None self.current_problem = None
def make_widgets(self): frm1 = Frame(self) frm1.pack(side=TOP, fill=X) Entry(frm1, textvariable=self._root_path_var, font=DEFAULT_FONT).pack(side=LEFT, fill=X, expand=YES) Button(frm1, text='Add directory', font=DEFAULT_FONT, command=lambda: self._root_path_var.set(askdirectory(title='Add directory'))).pack(side=RIGHT) frm2 = Frame(self) frm2.pack(side=TOP, fill=X) keyword_ent = Entry(frm2, textvariable=self._keyword_var, font=DEFAULT_FONT) keyword_ent.pack(side=LEFT, fill=X, expand=YES) Button(frm2, text='Find', font=DEFAULT_FONT, command=self.find).pack(side=RIGHT) vs = Scrollbar(self) hs = Scrollbar(self) self._listbox = Listbox(self) vs.pack(side=RIGHT, fill=Y) vs.config(command=self._listbox.yview) hs.pack(side=BOTTOM, fill=X) hs.config(command=self._listbox.xview, orient='horizontal') self._listbox.config(yscrollcommand=vs.set, xscrollcommand=hs.set, font=DEFAULT_FONT) self._listbox.pack(fill=BOTH, expand=YES) self._listbox.bind('<Double-1>', self._navigate_to)
from tkinter import Listbox, END, Button, ANCHOR, Label, Frame, Scrollbar, VERTICAL, RIGHT, Y, Tk, MULTIPLE import tkinter as tk root = tk.Tk() root.geometry("600x640") root.config(bg="#353130") #! selcet mode CHECK LINE 19 20 # Create Frame my_frame = Frame(root) my_frame.pack() #scroll bar scroll_bar_4_my_listbox = Scrollbar(my_frame, orient=VERTICAL) scroll_bar_4_my_listbox.pack(side=RIGHT, fill=Y) #? y is to fill UP and DOWN all the way #? pack in on RIGHT hand side #Listbox #* SELECT MODE = SINGLE IS AT DEFAULT. <OTHER OPTIONS> BROWSE, MULTIPLE, EXTENDED my_listbox = Listbox( my_frame, width=50, bg="#353130", fg="white", yscrollcommand=scroll_bar_4_my_listbox.set, selectmode=MULTIPLE) #?yscrollcommand -> is for horizontal scrollbar my_listbox.pack(pady=15) ## coz of my_listbox no defined so got to put it here scroll_bar_4_my_listbox.config(command=my_listbox.yview)
class MainInterface(ttk.Frame): def __init__(self, controller, *args, **kwargs): ttk.Frame.__init__(self, *args, **kwargs) self.place(relwidth=1, relheight=1) self.controller = controller self.image = None self.raw_image = None self.edited_image = None self.tiles = [] self.save_image = ImageTk.PhotoImage( load_image_object_from_bytes_array(FLOPPY_BYTES)) left_column_container = Frame(self) left_column_container.pack(side="left", fill="both", expand=True) canvas_container = Frame(left_column_container) canvas_container.pack(side="top", fill="both", expand=True) self.canvas_height = 720 self.canvas_width = 1080 self.canvas = ResizableCanvas(canvas_container, relief="sunken") self.canvas.config(width=self.canvas_width, height=self.canvas_height, highlightthickness=0) self.canvas.place(relwidth=1, relheight=1) self.canvas_frame = Frame(self.canvas, border=0, highlightthickness=0) self.canvas_frame.config(width=self.canvas_width, height=self.canvas_height) self.canvas.create_window(0, 0, window=self.canvas_frame, anchor='nw') self.canvas.bind("<Motion>", self.on_mouse_move) self.canvas.bind("<Button-1>", self.on_left_click) sidebar_container = Frame(self) sidebar_container.pack(side="right", fill="y", expand=False) sidebar_container.configure(width=50) self.data_type_var = StringVar() self.data_type_var.set(DATA_OPTIONS[0]) self.data_type_dropdown = OptionMenu(sidebar_container, self.data_type_var, *DATA_OPTIONS) self.data_type_dropdown.pack(side="top", fill="x", expand=False, padx=2) self.smoothing_button = LabeledCheckbutton("7-Day Smoothing", True, sidebar_container) self.smoothing_button.pack(side="top", fill="x", expand=False, padx=2) self.us_button = LabeledCheckbutton("Total US Graph", True, sidebar_container, command=self.on_us_set) self.us_button.pack(side="top", fill="x", expand=False, padx=2) listbox_container = Frame(sidebar_container) listbox_container.pack(side="top", fill="y", expand=True) self.scrollbar = Scrollbar(listbox_container) self.scrollbar.pack(side="right", fill="y", padx=(0, 2)) self.listbox = Listbox(listbox_container, selectmode="multiple") self.listbox.pack(side="right", fill="y", expand=True, padx=(2, 0)) self.build_button = Button( sidebar_container, text="Build Graph", command=lambda: self.controller.threader.do(self.on_build)) self.build_button.pack(side="top", fill="x", expand=False, padx=4, pady=4) for r in REGIONS: self.listbox.insert("end", r) self.listbox.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.listbox.yview) self.bind("<Configure>", self.on_configure) self.on_us_set() def first_run_async(): save_button = Tile(self, self.save_image, self.save_image, self.save) save_button.set_dimensions(10, 10, 25, 25) self.tiles.append(save_button) self.place_tiles() self.on_build() self.after(10, self.on_configure) self.controller.threader.do(first_run_async, []) def on_us_set(self): if self.us_button.get(): self.listbox.configure(state="disable") else: self.listbox.configure(state="normal") def resize_canvas_image(self): if not self.raw_image: return picwidth = self.canvas.winfo_width() wpercent = (picwidth / float(self.raw_image.size[0])) hsize = int((float(self.raw_image.size[1]) * float(wpercent))) if picwidth < 1 or hsize < 1: return picheight = self.canvas.winfo_height() if hsize > picheight: hpercent = (picheight / float(self.raw_image.size[1])) wsize = int((float(self.raw_image.size[0]) * float(hpercent))) self.edited_image = self.raw_image.resize((wsize, picheight), Image.ANTIALIAS) else: self.edited_image = self.raw_image.resize((picwidth, hsize), Image.ANTIALIAS) self.image = ImageTk.PhotoImage(image=self.edited_image) self.canvas.create_image(self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2, anchor="center", image=self.image) self.place_tiles() def on_build(self, event=None): self.build_button.configure(state="disable") self.canvas.delete("all") t = self.canvas.create_text(self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2, text="Building graph,\nplease be patient.", anchor="center", font=("Sans", 30), fill="#333333", justify="center") self.winfo_toplevel().update_idletasks() #Refresh screen self.edited_image = None region = [] if not self.us_button.get(): indx = self.listbox.curselection() if indx: for i in indx: r = self.listbox.get(i) region.append(r) else: region = "US" else: region = "US" smooth = self.smoothing_button.get() datakey = DATA_OPTIONS_MAP[self.data_type_var.get()] if self.controller.client: fn = self.controller.graph_function(self.controller.api_url, region, smooth, datakey=datakey) else: fn = self.controller.graph_function(region, smooth, datakey=datakey) self.raw_image = Image.open(fn) self.resize_canvas_image() self.build_button.configure(state="normal") self.after(100, lambda: self.canvas.delete(t)) def on_configure(self, event=None): if not self.edited_image: self.resize_canvas_image() self.after(50, self.resize_canvas_image) def place_tiles(self, event=None): for t in self.tiles: for r in t.references: self.canvas.delete(r) for r in t.active_references: self.canvas.delete(r) self.place_tile(t) def place_tile(self, tile): if tile.active: tile.references.append( self.canvas.create_image(tile.x + 4, tile.y + 4, anchor="nw", image=tile.active_image)) self.activate_tile() else: tile.references.append( self.canvas.create_image(tile.x + 4, tile.y + 4, anchor="nw", image=tile.inactive_image)) def on_mouse_move(self, event): y = int(event.y + (float(self.canvas.yview()[0]) * self.canvas_height)) x = event.x for t in self.tiles: if t.is_in_range(x, y): if t.active: continue else: t.activate() else: t.deactivate() def activate_tile(self, tile): tile.active_references.extend([ self.canvas.create_rectangle(tile.x - 1, tile.y - 1, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=2), ]) def deactivate_tile(self, tile): for r in tile.active_references: self.canvas.delete(r) def on_left_click(self, event): for t in self.tiles: if t.on_click(event.x, event.y): break def save(self): SaveMenu(self.controller, self.raw_image)
(scrollregion=tab2_scroll_canvas.bbox('all'))) tab2_scroll_canvas.create_window((0, 0), window=scrollable_frame, anchor='nw') tab2_scroll_canvas.configure(yscrollcommand=scroll.set) global tab2_canvas_files tab2_canvas_files = tk.Canvas(scrollable_frame) tab2_canvas_files.config(relief=FLAT, bg='#ffffff', \ highlightthickness=0, bd=0) tab2_canvas_files.pack(fill=BOTH, expand=True) tab2_files_frame.grid(row=1, column=0, columnspan=2, rowspan=2, \ sticky=N+S+E+W, padx=(10,0), pady=(10,0)) tab2_canvas.grid_columnconfigure(1, weight=0) tab2_canvas.grid_rowconfigure(1, weight=0) tab2_scroll_canvas.pack(side=LEFT, fill=BOTH, expand=True) scroll.pack(side=RIGHT, fill=Y) global dose_response_save_calibration_button global doseResponse_dpi doseResponse_dpi = StringVar() doseResponse_dpi.set("127") global dose_response_var1 dose_response_var1 = IntVar() dose_response_var1.set(1) global dose_response_var2 dose_response_var2 = IntVar() dose_response_var2.set(1)
def __init__(self, root): # Configure the root object for the Application self.root = root self.root.title(88 * " " + "GUI DICTIONARY") self.root.geometry("690x610+300+50") self.root.resizable(width=False, height=False) self.root.config(bg='#2A2C2B') # Create an instance of Database Class self.dbms_inst = Database("Dict_personal.db") # ================================VARIABLES============================ self.word_to_add = StringVar() self.word_description = StringVar() # ================================FRAMES=============================== # Create a Main Frame main_frame = Frame(self.root, bd=10, width=770, height=700, relief=RIDGE, bg='cadet blue') main_frame.grid() # Create a Title Frame title_frame = Frame(main_frame, bd=7, padx=10, pady=10, width=770, height=100, relief=RAISED) title_frame.grid(row=0, column=0, padx=2, pady=2, sticky="nsew") # Create a Data Frame data_frame = Frame(main_frame, bd=5, width=770, height=700, padx=10, pady=10, relief=RAISED) data_frame.grid(row=1, column=0, padx=2, pady=2, sticky="nsew") # ======================LABEL WIDGET=================================== self.lblWordToAdd = Label(title_frame, font=('Arial', 12, 'bold'), text="Enter your word ", fg="black", padx=1, pady=1, borderwidth=0) self.lblWordToAdd.grid(row=0, column=0, sticky=W) self.lblDescription = Label(title_frame, font=('Arial', 12, 'bold'), text="Enter description ", wraplength=500, padx=1, pady=1, borderwidth=0, fg="black") self.lblDescription.grid(row=1, column=0, sticky=W) # ======================ENTRY WIDGET=================================== self.entWordToAdd = Entry(title_frame, font=('Arial', 12, 'bold'), textvariable=self.word_to_add, bd=5, justify='left', width=25) self.entWordToAdd.grid(row=0, column=1, sticky=W, padx=5) self.entDescription = Entry(title_frame, width=25, bd=5, font=('Arial', 12, 'bold'), justify='left', textvariable=self.word_description) self.entDescription.grid(row=1, column=1, sticky=W, padx=5) # ======================TREEVIEW WIDGET================================ # Style the TreeView style = ttk.Style() # Use a theme style.theme_use("winnative") # Modify the font of the body style.configure('mystyle.Treeview', background="white", foreground="black", rowheight=25, borderwidth='4', fieldbackground="white", font=('Helvetica', 10)) # Modify the font of the headings style.configure("mystyle.Treeview.Heading", font=('Calibri', 13, 'bold')) # Change Selected Color style.map('mystyle.Treeview', background=[('selected', 'blue')]) # Set the treeview self.word_database = ttk.Treeview(data_frame, height=15, style="mystyle.Treeview", selectmode="extended", show="headings") # Define our columns self.word_database['columns'] = ('Word', 'Meaning') # Adding Vertical Scrollbar to Treeview scroll_y = ttk.Scrollbar(data_frame, orient=VERTICAL, command=self.word_database.yview) scroll_y.pack(side=RIGHT, fill=Y) self.word_database.configure(yscrollcommand=scroll_y.set) # Adding Horizontal Scrollbar to Treeview scroll_x = Scrollbar(data_frame, orient=HORIZONTAL, command=self.word_database.xview) scroll_x.pack(side=BOTTOM, fill=X) self.word_database.configure(xscrollcommand=scroll_x.set) # Assigning the heading names to the respective columns self.word_database.heading("#0", text="", anchor=W) self.word_database.heading("Word", text="Keyword", anchor=W) self.word_database.heading("Meaning", text="Description", anchor=W) # Format the columns - Assign the width to respective columns self.word_database.column('#0', stretch='NO', minwidth=0, width=0) self.word_database.column("Word", stretch='YES', width=100, minwidth=80) self.word_database.column("Meaning", stretch='YES', width=500, minwidth=100) self.word_database.tag_configure('oddrow', background="lightblue") self.word_database.tag_configure('evenrow', background="white") # Calling pack method w.r.to treeview self.word_database.pack(side="left", fill=BOTH, expand=TRUE) # ====================== BUTTONS WIDGET=================================== # Add Button add_button = Button(title_frame, text="Add Data", command=self.addData, font=('Helvetica', 10, 'bold'), height=2, width=13, bd=4) add_button.grid(row=0, column=2, padx=2, pady=2, sticky="nsew") # Delete Button del_button = Button(title_frame, text="Delete Multiple", font=('Helvetica', 10, 'bold'), height=2, width=13, bd=4, command=self.deleteMultipleRecords) del_button.grid(row=1, column=2, padx=2, pady=2, sticky="nsew") # Search Button search_button = Button(title_frame, text="Search Data", font=('Helvetica', 10, 'bold'), height=2, width=13, bd=4, command=self.searchData) search_button.grid(row=0, column=3, padx=2, pady=2, sticky="nsew") # Update Button updt_button = Button(title_frame, text="Update Data", font=('Helvetica', 10, 'bold'), height=2, width=13, bd=4, command=self.updateData) updt_button.grid(row=1, column=3, padx=2, pady=2, sticky="nsew")
Label(ftop, textvariable=pagetextvar).grid(row=1, column=3) r1 = Radiobutton(ftop, text='向左翻九十', variable=radio_var, value='270') r1.grid(row=2, column=0) r2 = Radiobutton(ftop, text='向右翻九十', variable=radio_var, value='90') r2.grid(row=2, column=1) r2 = Radiobutton(ftop, text='翻一百八', variable=radio_var, value='180') r2.grid(row=2, column=2) Button(ftop, text='一键翻转', command=lambda: display_pages('allfile')).grid(row=2, column=4) lb = Listbox(fleft, listvariable=lb_list) lb.pack(side=LEFT, fill=BOTH, expand=YES) scroll = Scrollbar(fleft, command=lb.yview) scroll.pack(side=RIGHT, fill=Y, pady=10) b0 = Button(fright, text='浏览器查看', command=threading_open_page) b0.grid(row=0, column=4) b3 = Button(fright, text='向左翻九十', command=lambda: rotate_one_page('270')) b3.grid(row=3, column=4) b4 = Button(fright, text='向右翻九十', command=lambda: rotate_one_page('90')) b4.grid(row=4, column=4) b5 = Button(fright, text='翻一百八', command=lambda: rotate_one_page('180')) b5.grid(row=5, column=4) Button(fbot, text='清除查看文件', command=del_dir).pack() Button(fbot, text='退 出', command=tk.quit).pack()
def visualize(self): """Pops up a window showing a transition diagram. Requires graphviz. Under MacOS Sierra, you'll need to upgrade to 10.12.2 or newer.""" import subprocess from tkinter import (Tk, Canvas, PhotoImage, Scrollbar, HORIZONTAL, VERTICAL, X, Y, BOTTOM, RIGHT, LEFT, YES, BOTH, ALL) import base64 def escape(s): return '"{}"'.format(s.replace('\\', '\\\\').replace('"', '\\"')) dot = [] dot.append("digraph {") dot.append('START[label="",shape=none];') index = {} for i, q in enumerate(self.states): index[q] = i attrs = {'label': escape(str(q)), 'fontname': 'Courier'} if q == self.accept: attrs['peripheries'] = 2 dot.append('{} [{}];'.format( i, ",".join("{}={}".format(k, v) for (k, v) in attrs.items()))) dot.append("START->{};".format(index[self.start])) for q in self.states: ts = collections.defaultdict(list) for t in self.transitions_from.get(q, []): ts[t.r].append(t) for r in ts: if len(ts[r]) > 8: label = "\n".join(":".join(map(str, t.a)) for t in ts[r][:5]) + "\n..." else: label = "\n".join(":".join(map(str, t.a)) for t in ts[r]) dot.append('{}->{}[label={},fontname=Courier];'.format( index[q], index[r], escape(label))) dot.append("}") dot = "\n".join(dot) proc = subprocess.run(["dot", "-T", "gif"], input=dot.encode("utf8"), stdout=subprocess.PIPE) if proc.returncode == 0: root = Tk() scrollx = Scrollbar(root, orient=HORIZONTAL) scrollx.pack(side=BOTTOM, fill=X) scrolly = Scrollbar(root, orient=VERTICAL) scrolly.pack(side=RIGHT, fill=Y) canvas = Canvas(root) image = PhotoImage(data=base64.b64encode(proc.stdout)) canvas.create_image(0, 0, image=image, anchor="nw") canvas.pack(side=LEFT, expand=YES, fill=BOTH) canvas.config(xscrollcommand=scrollx.set, yscrollcommand=scrolly.set) canvas.config(scrollregion=canvas.bbox(ALL)) scrollx.config(command=canvas.xview) scrolly.config(command=canvas.yview) root.mainloop()
class AppPage(ttk.Frame): def __init__(self, controller, repo, *args, **kwargs): ttk.Frame.__init__(self, *args, **kwargs) self.controller = controller self.repo = repo self.thumbnails = [] self.tiles = [] self.draw_session = 0 self.back_button_reference = None self.back_image = load_image_object_from_bytes_array(back_image) self.back_button = ImageTk.PhotoImage(self.back_image) self.notfound_image = load_image_object_from_bytes_array( notfound_image) canvas_container = Frame(self) canvas_container.pack(side="top", fill="both", expand=True) self.canvas_height = 720 self.canvas_width = 1080 self.canvas = ResizableCanvas(canvas_container, relief="sunken", background="#333333") self.canvas.config(width=self.canvas_width, height=self.canvas_height, highlightthickness=0) self.scrollbar = Scrollbar(canvas_container) self.scrollbar.config(command=self.on_scroll_bar) self.canvas.config(yscrollcommand=self.scrollbar.set) self.scrollbar.pack(side="right", fill="y") self.canvas.pack(side="right", expand=True, fill="both") self.canvas_frame = Frame(self.canvas, border=0, highlightthickness=0) self.canvas_frame.bind("<MouseWheel>", self._on_mouse_wheel) self.canvas_frame.config(width=self.canvas_width, height=self.canvas_height) self.canvas.create_window(0, 0, window=self.canvas_frame, anchor='nw') self.canvas.bind("<MouseWheel>", self._on_mouse_wheel) self.canvas.config(scrollregion=(0, 0, self.canvas_height, self.canvas_height)) # self.canvas.bind("<Enter>", self.mouse_enter) # self.canvas.bind("<Leave>", self.mouse_leave) self.canvas.bind("<Motion>", self.mouse_move) self.canvas.bind("<Button-1>", self.on_click) self.canvas.bind("<Configure>", self.on_configure) self.bind("<MouseWheel>", self._on_mouse_wheel) self.build_tiles() self.controller.threader.add(self.refresh) def on_configure(self, event=None): self.refresh() print("Configured") self.canvas.config(width=self.winfo_width(), height=self.winfo_height(), highlightthickness=0) # def mouse_enter(self, event): pass # def mouse_leave(self, event): pass def on_click(self, event): y = int(event.y + (float(self.canvas.yview()[0]) * self.canvas_height)) x = event.x #Check back button left_bound = 10 right_bound = left_bound + self.back_image.size[0] top_bound = float(self.canvas.yview()[0] * self.canvas_height) + 10 bottom_bound = top_bound + self.back_image.size[1] if x > left_bound and x < right_bound: if y > top_bound and y < bottom_bound: self.exit() return for t in self.tiles: if t.is_in_range(x, y): print("Spawning_details") p = DetailPage(self.controller, self.repo, t.package, self) p.place(relwidth=1, relheight=1) else: t.deactivate() def mouse_move(self, event): y = int(event.y + (float(self.canvas.yview()[0]) * self.canvas_height)) x = event.x for t in self.tiles: if t.is_in_range(x, y): if t.active: continue else: t.activate() self.update_overhead( ) #Don't let overhead icons get overwritten else: t.deactivate() def build_tiles(self, event=None): self.tiles = [] for p in self.repo.all: t = Tile(self, p) self.tiles.append(t) def refresh(self, event=None): self.draw_session += 1 this_ds = self.draw_session print(f"Draw session {self.draw_session}") self.controller.threader.new_session() self.canvas.delete("all") self.update_overhead() i = 0 y_offset = 10 y_padding = 4 x_padding = 4 tile_height = 200 tile_width = 200 framewidth = self.canvas.winfo_width() - x_padding self.canvas_frame.config(width=framewidth) # Get integer number of tiles fittable in the window maxperrow = framewidth // (tile_width + x_padding) #If there's not enough room to build anything if not maxperrow: return print("Not_enough_room") maxwidth = (maxperrow) * tile_width + maxperrow * x_padding filler_space = framewidth - maxwidth try: filler_space = filler_space / (maxperrow + 1) except ZeroDivisionError: return _x = 0 _y = 0 def handle_tile(t, x, y, ds): if not ds == self.draw_session: return t.set_dimensions(x, y, tile_width, tile_height) try: self.place_tile(t) except Exception as e: pass #Usually only errors due to the canvas not existing any more #Tile tiles ##TODO: CALCULATE PRIORITY TILES TO RENDER IN CASE OF NON-TOP-OF-CANVAS REDRAW for t in self.tiles: place_x = _x * tile_width + (_x + 1) * x_padding + ( _x + 1) * filler_space place_y = _y * tile_height + y_offset + (_y + 1) * y_padding self.controller.threader.add(handle_tile, [t, place_x, place_y, this_ds]) i += 1 _x += 1 if _x == maxperrow: _x = 0 _y += 1 _y += 1 height = _y * tile_height + y_offset + (_y + 1) * y_padding frameheight = self.canvas_frame.winfo_height() height = height if height > frameheight else frameheight self.canvas_height = height self.canvas_frame.config(width=200, height=self.winfo_height()) self.canvas.config(scrollregion=(0, 0, 200, self.canvas_height)) self.refreshing = False def place_tile(self, tile): try: downloads = tile.package.get("app_dls", "n/a") title = tile.package["title"] if len( tile.package["title"] ) < 33 else tile.package["title"][:20] + "..." author = tile.package["author"] if len( tile.package["author"] ) < 26 else tile.package["author"][:23] + "..." version = tile.package["version"] if len( tile.package["version"] ) < 25 else tile.package["version"][:17] + "..." tile.references.extend([ self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, fill="#7F7F7F"), self.canvas.create_line(tile.x + 10, tile.y + 130, tile.x + tile.width - 10, tile.y + 130, width=4), self.canvas.create_text(tile.x + 5, tile.y + 135, anchor="nw", text=title), self.canvas.create_text(tile.x + 5, tile.y + 150, anchor="nw", text=f"By - {author}"), self.canvas.create_text(tile.x + 5, tile.y + 165, anchor="nw", text=f"Version - {version}"), self.canvas.create_text(tile.x + 5, tile.y + 180, anchor="nw", text=f"Downloads - {downloads}"), ]) if tile.active: self.activate_tile() if not tile.thumbnail: icon = self.repo.getPackageIcon(tile.package["name"]) tile.thumbnail = Image.open( icon) if icon else self.notfound_image art_image = tile.thumbnail maxwidth = tile.width - 8 maxheight = tile.width - 8 wpercent = (maxwidth / float(art_image.size[0])) hsize = int((float(art_image.size[1]) * float(wpercent))) new_image = art_image.resize((maxwidth, hsize), Image.ANTIALIAS) if new_image.size[1] > maxheight: hpercent = (maxheight / float(art_image.size[1])) wsize = int((float(art_image.size[0]) * float(hpercent))) new_image = art_image.resize((wsize, maxheight), Image.ANTIALIAS) thumbnail = ImageTk.PhotoImage(new_image) self.thumbnails.append(thumbnail) tile.references.append( self.canvas.create_image(tile.x + 4, tile.y + 4, anchor="nw", image=thumbnail)) except RuntimeError: pass def activate_tile(self, tile): tile.active_references.extend([ self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=4), self.canvas.create_rectangle(tile.x + 4, tile.y + 4, tile.x + tile.width - 5, tile.y + tile.height - 5, fill="#424548"), self.canvas.create_text(tile.x + 8, tile.y + 8, text=tile.package["description"], anchor="nw", width=tile.width - 16, fill="#CCCCCC") ]) def deactivate_tile(self, tile): for r in tile.active_references: self.canvas.delete(r) def _on_mouse_wheel(self, event): if platform.system() == 'Windows': self.canvas.yview_scroll(-1 * int(event.delta / 120), 'units') elif platform.system() == 'Darwin': self.canvas.yview_scroll(-1 * int(event.delta), 'units') else: if event.num == 4: self.canvas.yview_scroll(-1, 'units') elif event.num == 5: self.canvas.yview_scroll(1, 'units') self.update_overhead() def on_scroll_bar(self, move_type, move_units, __=None): if move_type == "moveto": self.canvas.yview("moveto", move_units) self.update_overhead() def update_overhead(self): self.canvas.delete(self.back_button_reference) self.back_button_reference = self.canvas.create_image( 10, float(self.canvas.yview()[0] * self.canvas_height) + 10, anchor="nw", image=self.back_button) def exit(self): self.draw_session += 1 #Increase draw session to prevent unfinished draws from attempting self.controller.threader.new_session() #Remove qued threads self.destroy() #destroy window
class AutoUploadPage(tk.Frame): # 继承Frame类 def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # 存储任务列表 self.task_dict = {} self.task_list = [] self.onduty_list = [] self.qb = '' self.is_rss_mode = False self.t = 'Recorde_rss' self.refresh_t = 'Recorde_task_list' # 布局组件的定义 self.var_link = StringVar() self.entry_link = tk.Entry(self, textvariable=self.var_link, width=58, borderwidth=3, font=('Helvetica', '12')) self.entry_link.bind('<Return>', self.enter_add) self.button_add = tk.Button(self, text='Add', font=('Helvetica', '12'), width=6, command=self.add_task_by_click) self.frame_m = Frame(self) self.scrollBar = Scrollbar(self.frame_m) self.tree = Treeview(self.frame_m, columns=('c1', 'c2', 'c3'), show="headings", yscrollcommand=self.scrollBar.set) self.btnDelete = tk.Button(self, text='删除任务', command=self.delete_task) self.btnRefresh = tk.Button(self, text='备份任务', command=self.bak_task) self.rsshandler = get_rss_info.RssLinkHandler() self.config_dl = self.controller.config_dl self.create_page() def create_page(self): # 添加种子部分 # LEFT self.entry_link.place(x=30, y=30, width=600, height=30) self.var_link.set('请输入种子详情链接:') self.entry_link.bind('<FocusIn>', self.on_entry_click) self.entry_link.bind('<FocusOut>', self.on_focus_out) self.entry_link.config(fg='grey') self.button_add.place(x=640, y=28, width=80, height=30) # 管理种子部分 self.frame_m.place(x=28, y=80, width=700, height=450) # 在Frame容器中创建滚动条 self.scrollBar.pack(side=RIGHT, fill=Y) # 在Frame容器中使用Treeview组件实现表格功能 # Treeview组件,三列,显示表头,带垂直滚动条 # 设置每列宽度和对齐方式 self.tree.column('c1', width=400, anchor='w') self.tree.column('c2', width=140, anchor='center') self.tree.column('c3', width=120, anchor='center') # 设置每列表头标题文本 self.tree.heading( 'c1', text='种子链接', command=lambda: self.treeview_sort_column(self.tree, 'c1', False)) self.tree.heading( 'c2', text='添加时间', command=lambda: self.treeview_sort_column(self.tree, 'c2', False)) self.tree.heading( 'c3', text='状态', command=lambda: self.treeview_sort_column(self.tree, 'c3', False)) # 左对齐,纵向填充 self.tree.pack(side=LEFT, fill=Y) self.tree.bind('<Double-1>', self.treeviewclick) # Treeview组件与垂直滚动条结合 self.scrollBar.config(command=self.tree.yview) # 删除按钮 self.btnDelete.place(x=160, y=550, width=120, height=30) # 刷新按钮 self.btnRefresh.place(x=460, y=550, width=120, height=30) def on_entry_click(self, event): """function that gets called whenever entry is clicked""" if self.var_link.get() == '请输入种子详情链接:': self.var_link.set('') # delete all the text in the entry self.entry_link.config(fg='black') def on_focus_out(self, event): if self.var_link.get() == '': self.var_link.set('请输入种子详情链接:') self.entry_link.config(fg='grey') # 添加下载任务 def add_task_by_click(self): detail_link = self.var_link.get() self.add_task_by_link(detail_link) # 重置界面 self.var_link.set('') self.entry_link.config(fg='grey') def all_time_refresh(self): while True: if len(self.onduty_list) == 0: break else: time.sleep(2) self.refresh_task() def enter_add(self, event): self.add_task_by_click() # 删除选中项的按钮 def delete_task(self): if not self.tree.selection(): tk.messagebox.showerror('抱歉', '你还没有选择,不能删除') return for item in self.tree.selection(): detail_link = self.tree.item(item, 'values')[0] statu = self.tree.item(item, 'values')[2] if statu not in ['发布成功', '任务丢失']: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '发布成功' and hash_info: # 判断有没有下载完 torrent = self.qb.get_torrent(infohash=hash_info) if torrent['completion_date'] == -1: self.qb.delete_permanently(hash_info) try: commen_component.stop_thread(chosen_task) except ValueError: pass except SystemError: pass self.task_dict.pop(detail_link) self.task_list.remove(detail_link) if len(self.onduty_list) == 0: try: commen_component.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) self.tree.delete(item) # 更新所有种子的下载状态 def refresh_task(self): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_addtime = self.tree.item(item, 'values')[1] value_statu = self.tree.item(item, 'values')[2] if value_link in self.task_dict.keys(): value_statu_now = self.task_dict[value_link].get_statu() if not value_statu == value_statu_now: self.tree.item(item, values=(value_link, value_addtime, value_statu_now)) if value_statu_now == '发布成功' or value_statu_now == '任务丢失': try: commen_component.stop_thread( self.task_dict[value_link]) except ValueError: pass except SystemError: pass self.onduty_list.remove(value_link) self.task_dict.pop(value_link) if len(self.onduty_list) == 0: try: commen_component.stop_thread(self.refresh_t) except ValueError: pass except SystemError: pass def treeviewclick(self, event): selected_item = self.tree.selection()[0] link = self.tree.item(selected_item, 'values')[0] webbrowser.open(link) def treeview_sort_column(self, tv, col, reverse): # Treeview、列名、排列方式 ll = [(tv.set(k, col), k) for k in tv.get_children('')] ll.sort(reverse=reverse) # 排序方式 for index, (val, k) in enumerate(ll): # 根据排序后索引移动 tv.move(k, '', index) tv.heading(col, command=lambda: self.treeview_sort_column( tv, col, not reverse)) # 重写标题,使之成为再点倒序的标题 # 添加RSS任务 def add_rss_task(self): while True: self.rsshandler.change_refresh_time(self.config_dl['refresh_time']) self.rsshandler.now_time = '' entries_list = self.rsshandler.get_entries( self.config_dl['Max_Size']) for item in entries_list: detail_link = item['link'] if detail_link in self.task_list: continue add_time = datetime.datetime.now().strftime( '%Y/%m/%d %H:%M:%S') values = [detail_link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_methods.AutoSeed(self.qb, item, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread( target=self.all_time_refresh, args=()) self.refresh_t.start() if int(self.config_dl['refresh_time']) == 0: sleep(600) else: sleep(int(self.config_dl['refresh_time']) * 60) # 重新开启RSS def reopen_rss(self): try: commen_component.stop_thread(self.t) except ValueError: pass except SystemError: pass self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True tk.messagebox.showinfo('提示', 'RSS模式已经重启') def init_qb(self): self.qb = self.controller.qb self.get_bak_task() self.check_rss_mode() # 检查RSS是否开启 def check_rss_mode(self): if self.config_dl['rss_open']: if not self.is_rss_mode: self.t = threading.Thread(target=self.add_rss_task, args=()) self.t.start() self.is_rss_mode = True # tk.messagebox.showinfo('提示', 'RSS模式已经开启') return 'opened' else: return 'opened_already' else: if self.is_rss_mode: try: commen_component.stop_thread(self.t) except ValueError: pass except SystemError: pass # tk.messagebox.showinfo('提示', 'RSS模式已经关闭') self.is_rss_mode = False return 'closed' else: return 'closed_already' # 备份任务 def bak_task(self): self.refresh_task() bak_task = [] # 以列表的形式保存未完成的种子 task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] value_statu = self.tree.item(item, 'values')[2] if value_statu not in ['发布成功', '任务丢失']: task = self.task_dict[value_link] bak_task.append(task.get_origin_url()) try: commen_component.stop_thread(task) except ValueError: pass except SystemError: pass with open(USER_BAK_TASK_PATH, "wb") as bak_file: # with open with语句可以自动关闭资源 pickle.dump(bak_task, bak_file) def get_bak_task(self): try: with open(USER_BAK_TASK_PATH, "rb") as bak_file: bak_task = pickle.load(bak_file) if not bak_task: return for item in bak_task: if isinstance(item, dict): link = item['link'] else: link = item add_time = datetime.datetime.now().strftime( '%Y/%m/%d %H:%M:%S') values = [link, add_time, '准备下载'] self.tree.insert('', 'end', values=values) new_task = autoseed_methods.AutoSeed( self.qb, item, self.config_dl) self.task_dict[link] = new_task self.onduty_list.append(link) self.task_list.append(link) new_task.start() if len(self.onduty_list) == 1: self.refresh_t = threading.Thread( target=self.all_time_refresh, args=()) self.refresh_t.start() except FileNotFoundError: pass # 添加任务 def add_task_by_link(self, string, *args): detail_link = string # 禁止空或者误操作 if not detail_link or detail_link == '请输入种子详情链接:': return # 禁止重复添加的链接 if detail_link in self.task_list: messagebox.showerror('错误', '重复添加的链接!') return # 禁止不支持的网站 support_sign = commen_component.find_origin_site(detail_link) if support_sign == 0: messagebox.showerror('错误', '不支持的网站!') return torrent_id = commen_component.get_id(detail_link) if torrent_id == -1: messagebox.showerror('错误', '不是种子详情链接!') return # 显示任务到列表 add_time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S').replace('-', '/') values = [detail_link, add_time, '准备下载'] # 添加到尾部 self.tree.insert('', 'end', values=values) # 添加到首部 # self.tree.insert('', 0, values=values) # 添加任务到后台并开启 # 构造元祖实现远程判断 if args: detail_link_tuple = (args[0], detail_link) else: detail_link_tuple = detail_link new_task = autoseed_methods.AutoSeed(self.qb, detail_link_tuple, self.config_dl) new_task.start() self.task_dict[detail_link] = new_task self.task_list.append(detail_link) self.onduty_list.append(detail_link) if len(self.onduty_list) == 1: self.refresh_t = threading.Thread(target=self.all_time_refresh, args=()) self.refresh_t.start() return '任务已经添加' # 远程获取任务状态 def get_statu_by_link(self, link): task_all = self.tree.get_children() for item in task_all: value_link = self.tree.item(item, 'values')[0] if value_link == link: value_statu = self.tree.item(item, 'values')[2] return value_statu return 'no result' # 远程取消任务 def cancle_task_by_link(self, detail_link): find = False task_all = self.tree.get_children() for item in task_all: link = self.tree.item(item, 'values')[0] if link == detail_link: self.tree.delete(item) find = True break if find: chosen_task = self.task_dict[detail_link] hash_info = chosen_task.get_hash_info() if chosen_task.get_statu() != '发布成功' and hash_info: self.qb.delete_permanently(hash_info) else: return '任务还未开始或已经完成' try: commen_component.stop_thread(chosen_task) except ValueError: return '未知错误' except SystemError: return '未知错误' self.task_list.remove(detail_link) self.task_dict.pop(detail_link) if detail_link in self.onduty_list: self.onduty_list.remove(detail_link) return '取消成功' else: return '没找到任务' # 关掉RSS def close_rss(self): self.config_dl['rss_open'] = False self.check_rss_mode()
menu_bar.add_cascade(label='About', menu=about_menu) root.config(menu=menu_bar) shortcut_bar = Frame(root, height=25, background='light sea green') shortcut_bar.pack(expand='no', fill='x') line_number_bar = Text(root, width=4, padx=3, takefocus=0, border=0, background='khaki', state='disabled', wrap='none') line_number_bar.pack(side='left', fill='y') content_text = Text(root, wrap='word', undo=1) content_text.pack(expand='yes', fill='both') scroll_bar = Scrollbar(content_text) content_text.configure(yscrollcommand=scroll_bar.set) scroll_bar.config(command=content_text.yview) scroll_bar.pack(side='right', fill='y') content_text.bind('<Control-f>', find_text) content_text.bind('<Control-F>', find_text) content_text.bind('<Control-A>', select_all) content_text.bind('<Control-a>', select_all) content_text.bind('<Control-y>', redo) content_text.bind('<Control-Y>', redo) root.mainloop()
def __init__(self, master, column_names, rows=None, column_weights=None, scrollbar=True, click_to_sort=True, reprfunc=None, cnf={}, **kw): """ Construct a new Table widget. :type master: Tkinter.Widget :param master: The widget that should contain the new table. :type column_names: list(str) :param column_names: A list of names for the columns; these names will be used to create labels for each column; and can be used as an index when reading or writing cell values from the table. :type rows: list(list) :param rows: A list of row values used to initialze the table. Each row value should be a tuple of cell values, one for each column in the row. :type scrollbar: bool :param scrollbar: If true, then create a scrollbar for the new table widget. :type click_to_sort: bool :param click_to_sort: If true, then create bindings that will sort the table's rows by a given column's values if the user clicks on that colum's label. :type reprfunc: function :param reprfunc: If specified, then use this function to convert each table cell value to a string suitable for display. ``reprfunc`` has the following signature: reprfunc(row_index, col_index, cell_value) -> str (Note that the column is specified by index, not by name.) :param cnf, kw: Configuration parameters for this widget's contained ``MultiListbox``. See ``MultiListbox.__init__()`` for details. """ self._num_columns = len(column_names) self._reprfunc = reprfunc self._frame = Frame(master) self._column_name_to_index = dict( (c, i) for (i, c) in enumerate(column_names)) # Make a copy of the rows & check that it's valid. if rows is None: self._rows = [] else: self._rows = [[v for v in row] for row in rows] for row in self._rows: self._checkrow(row) # Create our multi-list box. self._mlb = MultiListbox(self._frame, column_names, column_weights, cnf, **kw) self._mlb.pack(side="left", expand=True, fill="both") # Optional scrollbar if scrollbar: sb = Scrollbar(self._frame, orient="vertical", command=self._mlb.yview) self._mlb.listboxes[0]["yscrollcommand"] = sb.set # for listbox in self._mlb.listboxes: # listbox['yscrollcommand'] = sb.set sb.pack(side="right", fill="y") self._scrollbar = sb # Set up sorting self._sortkey = None if click_to_sort: for i, l in enumerate(self._mlb.column_labels): l.bind("<Button-1>", self._sort) # Fill in our multi-list box. self._fill_table()
def control_programs(_=0): try: program_list = session.query(Program).all() except: messagebox.showerror("Error", "Couldn't Fetch The Programs Table From The DB") session.rollback() return subwindow = Toplevel(window) subwindow.title("Programs") subwindow.geometry("1920x1080") canvas = Canvas(subwindow) scrollable_frame = Frame(canvas) scrollable_frame.bind( "<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")) ) canvas.create_window((0, 0), window=scrollable_frame, anchor="nw") scrollbary = Scrollbar(subwindow, orient="vertical", command=canvas.yview) scrollbarx = Scrollbar(subwindow, orient="horizontal", command=canvas.xview) canvas.configure(xscrollcommand=scrollbarx.set) canvas.configure(yscrollcommand=scrollbary.set) scrollbary.pack(side="right", fill="y") scrollbarx.pack(side="bottom", fill="x") canvas.pack(side="left", fill="both", expand=True) ttk.Label(scrollable_frame, text="index").grid(row=0, column=0, ipadx=1, ipady=1) ttk.Label(scrollable_frame, text="Program Name").grid( row=0, column=1, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program Publisher").grid( row=0, column=2, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program Release Date").grid( row=0, column=5, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program ID").grid( row=0, column=6, ipadx=1, ipady=1 ) for i in range(len(program_list)): ttk.Label(scrollable_frame, text=i + 1).grid( row=i + 1, column=0, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text=program_list[i].pname).grid( row=i + 1, column=1, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text=program_list[i].ppublisher).grid( row=i + 1, column=2, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text=program_list[i].preleaseddate).grid( row=i + 1, column=5, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text=program_list[i].pid).grid( row=i + 1, column=6, ipadx=1, ipady=1 ) ttk.Button( scrollable_frame, text="Remove", command=lambda pid=program_list[i].pid: remove_program(pid), ).grid(row=i + 1, column=7, ipadx=1, ipady=1)
return rows, domains, fieldnames = getdata() fformat = getfileformat() if fformat is False: return elif fformat == 'csv': writecsv(rows, domains, fieldnames) elif fformat == 'json': writejson(rows, domains, fieldnames) messagebox.showinfo("Info", "Data has been written successfully!") clearallselection() # treeview tree_scroll = Scrollbar(main_frame_1) tree_scroll.pack(side=tk.RIGHT, fill=tk.Y) tree = ttk.Treeview(main_frame_1, height=10, yscrollcommand=tree_scroll.set) tree.pack(expand=tk.YES, fill=tk.BOTH) style = ttk.Style() style.theme_use('clam') style.configure('Treeview', background='silver', foreground='black', rowheight=35, fieldbackground='silver') style.map('Treeview', background=[('selected', 'black')], foreground=[('selected', 'white')])
class Player(object): """Player class""" def __init__(self): """Initialisation of the Player object""" self.cfg = None self.db = None self.root = Tk() self.URL1L = StringVar(master=self.root) self.URL2L = StringVar(master=self.root) self.URL3L = StringVar(master=self.root) self.URL4L = StringVar(master=self.root) self.URL5L = StringVar(master=self.root) self.files = {} self.start() #---------------------------------------------------------------------# def start(self): """Start the Player""" print("*** Starting the Player ***") # Configuration self.cfg = Config() while not self.cfg.readConf() or not self.cfg.checkConf(): self.displayConfig() if self.cfg.readConf() and self.cfg.checkConf(): # Database self.db = Db(self.cfg) if self.db.openDb(): self.display() return(True) else: error("Database not open") return(False) else: error("Cannot read configuration file") return(False) #---------------------------------------------------------------------# def stop(self): """Stop the Player""" msg = "Do you want to quit Raspyplayer ?" if messagebox.askokcancel("Raspyplayer MC", msg): print("*** Stopping the Player ***") self.db.closeDb() self.root.destroy() #---------------------------------------------------------------------# def scanDB(self): """Add movies in DB""" print("*** Adding movies in database") self.db.initDb() scanFiles(self.db, self.cfg, self.cfg.PATH) self.db.commitDb() return(True) #---------------------------------------------------------------------# def loadAllMovies(self): """Load movies from DB""" self.files = self.db.getAllMovies() return(True) #---------------------------------------------------------------------# def loadSrcMovies(self, src): """Load movies matching search pattern""" self.files = self.db.getSrcMovies(src) return(True) #---------------------------------------------------------------------# def play(self, url, file): """Play a movie""" print("Playing {}".format(file)) if self.cfg.useOmx(): if not url: sub = file[0:-3] + "srt" if isfile(sub): cmd = self.cfg.OMXCMD2.format(self.cfg.OPT, self.cfg.OUT, sub, file) else: cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file) else: cmd = self.cfg.OMXCMD1.format(self.cfg.OPT, self.cfg.OUT, file) else: cmd = self.cfg.MPLRCMD.format(file) if DEBUG: print(cmd) system(cmd) return(True) #---------------------------------------------------------------------# def directPlay(self): """Direct play a file""" file = askopenfilename(title="Select a movie") if file: ps = playScreen() self.play(False, file) ps.destroy() return(True) #---------------------------------------------------------------------# def displayHelp(self): """Display help""" messagebox.showinfo("Help...", getHelp()) return(True) #---------------------------------------------------------------------# def displayConfig(self): """Display Config Window""" self.cfg.display(self) self.askToRefreshDataBase() return(True) #---------------------------------------------------------------------# def playSelection(self): """Play selected files""" sel = self.ui_files.curselection() ps = playScreen() for i in sel: f = self.ui_files.get(i) self.play(False, self.files[f]) ps.destroy() return(True) #---------------------------------------------------------------------# def playUrl(self, url): """Play selected url""" ps = playScreen() self.play(True, url) ps.destroy() return(True) #---------------------------------------------------------------------# def display(self): """Display the player""" self.createGui() self.cfg.toggleUrl(self) self.askToRefreshDataBase() self.root.mainloop() #---------------------------------------------------------------------# def askToRefreshDataBase(self): """Ask to refresh database""" msg = "Do you want to refresh the movies database ?" if messagebox.askokcancel("Raspyplayer MC", msg): self.refreshDataBase() else: self.refreshFilesList() return(True) #---------------------------------------------------------------------# def refreshDataBase(self): """Refresh the movies database""" if isdir(self.cfg.PATH): self.scanDB() self.refreshFilesList() return(True) #---------------------------------------------------------------------# def refreshFilesList(self): """Refresh the list of files""" src = self.ui_srcentry.get() # Empty variables : self.files = {} if self.ui_files.size() > 0: self.ui_files.delete(0, END) # Get files in DB : if src == "" or src == "*": if DEBUG: print("Get ALL") self.loadAllMovies() else: if DEBUG: print("Get '{}'".format(src)) self.loadSrcMovies(('%'+src+'%',)) # Sort results : liste = list() for f, p in self.files.items(): liste.append(f) liste.sort(key=str.lower) # Display result : for file in liste: self.ui_files.insert(END, file) return(True) #---------------------------------------------------------------------# def playUrl1(self): """Play URL 1""" self.playUrl(self.cfg.URL1) def playUrl2(self): """Play URL 2""" self.playUrl(self.cfg.URL2) def playUrl3(self): """Play URL 3""" self.playUrl(self.cfg.URL3) def playUrl4(self): """Play URL 4""" self.playUrl(self.cfg.URL4) def playUrl5(self): """Play URL 5""" self.playUrl(self.cfg.URL5) #---------------------------------------------------------------------# def evtPlay(self, evt): self.playSelection() def evtRefresh(self, evt): self.refreshFilesList() def evtScan(self, evt): self.askToRefreshDataBase() def evtCfg(self, cfg): self.displayConfig() def evtHelp(self, evt): self.displayHelp() def evtQuit(self, evt): self.stop() #---------------------------------------------------------------------# def createGui(self): """Create the GUI for Player""" print("*** Creating GUI ***") self.root.title("Raspyplayer Media Center v{}".format(VERSION)) font = Font(self.root, size=26, family='Sans') #self.root.attributes('-fullscreen', True) self.root.attributes('-zoomed', '1') # Top Frame (search group) self.ui_topframe = Frame(self.root, borderwidth=2) self.ui_topframe.pack({"side": "top"}) # Label search self.ui_srclabel = Label(self.ui_topframe, text="Search:", font=font) self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2) # Entry search self.ui_srcentry = Entry(self.ui_topframe, font=font) self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2) self.ui_srcentry.bind("<Return>", self.evtRefresh) # Button search self.ui_srcexec = Button(self.ui_topframe, text="Search", command=self.refreshFilesList, font=font) self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2) # Frame (contain Middle and Url frames) self.ui_frame = Frame(self.root, borderwidth=2) self.ui_frame.pack(fill=BOTH, expand=1) # Middle Frame (files group) self.ui_midframe = Frame(self.ui_frame, borderwidth=2) self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1) # Files liste and scrollbar self.ui_files = Listbox(self.ui_midframe, selectmode=EXTENDED, font=font) self.ui_files.pack(side=LEFT, fill=BOTH, expand=1) self.ui_files.bind("<Return>", self.evtPlay) self.ui_filesscroll = Scrollbar(self.ui_midframe, command=self.ui_files.yview) self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set) self.ui_filesscroll.pack(side=RIGHT, fill=Y) # Url Frame (url group) self.ui_urlframe = Frame(self.ui_frame, borderwidth=2) self.ui_urlframe.pack({"side": "right"}) # Button Url 1 self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L, command=self.playUrl1, font=font) self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2) # Button Url 2 self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L, command=self.playUrl2, font=font) self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2) # Button Url 3 self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L, command=self.playUrl3, font=font) self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2) # Button Url 4 self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L, command=self.playUrl4, font=font) self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2) # Button Url 5 self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L, command=self.playUrl5, font=font) self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2) # Bottom Frame (buttons group) self.ui_botframe = Frame(self.root, borderwidth=2) self.ui_botframe.pack({"side": "left"}) # Button Play self.ui_butplay = Button(self.ui_botframe, text="Play", command=self.playSelection, font=font) self.ui_butplay.grid(row=1, column=0, padx=2, pady=2) # Button Refresh self.ui_butscan = Button(self.ui_botframe, text="Scan", command=self.askToRefreshDataBase, font=font) self.ui_butscan.grid(row=1, column=1, padx=2, pady=2) # Button Direct Play self.ui_butdplay = Button(self.ui_botframe, text="Direct Play", command=self.directPlay, font=font) self.ui_butdplay.grid(row=1, column=2, padx=2, pady=2) # Button Config self.ui_butconf = Button(self.ui_botframe, text="Config", command=lambda : self.cfg.display(self), font=font) self.ui_butconf.grid(row=1, column=3, padx=2, pady=2) # Button Help self.ui_buthelp = Button(self.ui_botframe, text="Help", command=self.displayHelp, font=font) self.ui_buthelp.grid(row=1, column=4, padx=2, pady=2) # Button Quit self.ui_butquit = Button(self.ui_botframe, text="Quit", command=self.stop, font=font) self.ui_butquit.grid(row=1, column=5, padx=2, pady=2) # General bindings self.root.bind("<F1>", self.evtHelp) self.root.bind("<F2>", self.evtCfg) self.root.bind("<F3>", self.evtRefresh) self.root.bind("<F5>", self.evtScan) self.root.bind("<F12>", self.evtQuit) return(True)
class Edit(Frame): def __init__(self, master, valves): Frame.__init__(self, master, bg='sky blue', width=1366, height=768) self.master = master self.canvas = Canvas(self, height=630, width=1320, bg='sky blue') self.frame = Frame(self.canvas, bg='sky blue') self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview) self.scrollbar.configure(activebackground='DarkRed', background='red', width=40) self.canvas.configure(yscrollcommand=self.scrollbar.set, scrollregion=[0, 0, 1366, 800]) self.scrollbar.pack(side='right', fill='y') self.canvas.pack(side='left') self.canvas.create_window((0, 0), window=self.frame, anchor='nw') self.valves = valves self.frame.config(bg='sky blue') index = 0 while index < 10: self.frame.grid_rowconfigure(index, minsize=80) self.frame.grid_columnconfigure(index, minsize=30) index += 1 self.frame.grid_columnconfigure(3, minsize=130) self.frame.grid_columnconfigure(6, minsize=130) interval = Label(self.frame, text='RUN', width=6, font=('Lucida Console', 30)) interval.grid(row=0, column=2) interval.config(bg='sky blue', fg='RoyalBlue4') delay = Label(self.frame, text='DELAY', width=6, font=('Lucida Console', 30)) delay.grid(row=0, column=5) delay.config(bg='sky blue', fg='RoyalBlue4') self.seconds = [ IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar(), IntVar() ] for each in self.seconds: each.set(0) self.set_seconds() self.valve_label = [ Label(self.frame, textvariable=self.valves[0].get_name()), Label(self.frame, textvariable=self.valves[1].get_name()), Label(self.frame, textvariable=self.valves[2].get_name()), Label(self.frame, textvariable=self.valves[3].get_name()), Label(self.frame, textvariable=self.valves[4].get_name()), Label(self.frame, textvariable=self.valves[5].get_name()), Label(self.frame, textvariable=self.valves[6].get_name()), Label(self.frame, textvariable=self.valves[7].get_name()) ] row = 1 for each in self.valve_label: each.grid(row=row, column=0) each.config(width=8, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4') row += 1 self.minus_image = PhotoImage(file="img/minus.png").subsample(x=5, y=5) self.minusInterval = [ Button(self.frame, image=self.minus_image, command=lambda: self.subtract(0)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(1)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(2)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(3)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(4)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(5)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(6)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(7)), ] row = 1 for each in self.minusInterval: each.grid(row=row, column=1) each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white') row += 1 self.labelInterval = [ Label(self.frame, textvariable=self.seconds[0]), Label(self.frame, textvariable=self.seconds[1]), Label(self.frame, textvariable=self.seconds[2]), Label(self.frame, textvariable=self.seconds[3]), Label(self.frame, textvariable=self.seconds[4]), Label(self.frame, textvariable=self.seconds[5]), Label(self.frame, textvariable=self.seconds[6]), Label(self.frame, textvariable=self.seconds[7]) ] row = 1 for each in self.labelInterval: each.grid(row=row, column=2) each.config(width=4, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4') row += 1 self.plus_image = PhotoImage(file="img/plus.png").subsample(x=5, y=5) self.plusInterval = [ Button(self.frame, image=self.plus_image, command=lambda: self.add(0)), Button(self.frame, image=self.plus_image, command=lambda: self.add(1)), Button(self.frame, image=self.plus_image, command=lambda: self.add(2)), Button(self.frame, image=self.plus_image, command=lambda: self.add(3)), Button(self.frame, image=self.plus_image, command=lambda: self.add(4)), Button(self.frame, image=self.plus_image, command=lambda: self.add(5)), Button(self.frame, image=self.plus_image, command=lambda: self.add(6)), Button(self.frame, image=self.plus_image, command=lambda: self.add(7)), ] row = 1 for each in self.plusInterval: each.grid(row=row, column=3) each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white') row += 1 self.minusDelay = [ Button(self.frame, image=self.minus_image, command=lambda: self.subtract(8)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(9)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(10)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(11)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(12)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(13)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(14)), Button(self.frame, image=self.minus_image, command=lambda: self.subtract(15)), ] row = 1 for each in self.minusDelay: each.grid(row=row, column=4) each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white') each.config() row += 1 self.labelDelay = [ Label(self.frame, textvariable=self.seconds[8]), Label(self.frame, textvariable=self.seconds[9]), Label(self.frame, textvariable=self.seconds[10]), Label(self.frame, textvariable=self.seconds[11]), Label(self.frame, textvariable=self.seconds[12]), Label(self.frame, textvariable=self.seconds[13]), Label(self.frame, textvariable=self.seconds[14]), Label(self.frame, textvariable=self.seconds[15]) ] row = 1 for each in self.labelDelay: each.grid(row=row, column=5) each.config(width=4, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4') row += 1 self.plusDelay = [ Button(self.frame, image=self.plus_image, command=lambda: self.add(8)), Button(self.frame, image=self.plus_image, command=lambda: self.add(9)), Button(self.frame, image=self.plus_image, command=lambda: self.add(10)), Button(self.frame, image=self.plus_image, command=lambda: self.add(11)), Button(self.frame, image=self.plus_image, command=lambda: self.add(12)), Button(self.frame, image=self.plus_image, command=lambda: self.add(13)), Button(self.frame, image=self.plus_image, command=lambda: self.add(14)), Button(self.frame, image=self.plus_image, command=lambda: self.add(15)), ] row = 1 for each in self.plusDelay: each.grid(row=row, column=6) each.config(bg='SkyBlue4', activebackground='midnight blue') each.config() row += 1 self.motor_image = PhotoImage(file="img/motor.png").subsample(x=5, y=5) self.motor = [ Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(0)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(1)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(2)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(3)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(4)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(5)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(6)), Button(self.frame, text='MOTOR', image=self.motor_image, command=lambda: self.motor_on(7)) ] row = 1 for each in self.motor: each.grid(row=row, column=7) each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white') each.config() row += 1 self.adv_image = PhotoImage(file="img/options.png").subsample(x=5, y=5) self.adv = [ Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(0)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(1)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(2)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(3)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(4)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(5)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(6)), Button(self.frame, image=self.adv_image, command=lambda: self.motor_on(7)), ] row = 1 for each in self.adv: each.grid(row=row, column=8) each.config(bg='SkyBlue4', activebackground='midnight blue', fg='white') row += 1 self.set_seconds() self.lock() def lock(self): index = 0 while index < 8: self.minusInterval[index].config(state='disabled') self.minusDelay[index].config(state='disabled') self.plusInterval[index].config(state='disabled') self.plusDelay[index].config(state='disabled') self.motor[index].config(state='disabled') self.adv[index].config(state='disabled') index += 1 def set_seconds(self): index = 0 while index < 8: if self.valves[index].get_setting() == 'DEFAULT': interval = self.valves[index].get_interval() # setting seconds for runtime self.seconds[index].set(interval[0]) # setting seconds for delay self.seconds[index + 8].set(interval[1]) else: self.minusInterval[index].config(state='disabled') self.minusDelay[index].config(state='disabled') self.plusInterval[index].config(state='disabled') self.plusDelay[index].config(state='disabled') index += 1 def get_intervals(self): return self.seconds def motor_on(self, index): if self.minusDelay[index].cget('state') == 'normal': self.minusInterval[index].config(state='disabled') self.minusDelay[index].config(state='disabled') self.plusInterval[index].config(state='disabled') self.plusDelay[index].config(state='disabled') self.adv[index].config(state='disabled') self.seconds[index].set(0) self.seconds[index + 8].set(0) else: interval = self.valves[index].get_interval() self.minusInterval[index].config(state='normal') self.minusDelay[index].config(state='normal') self.plusInterval[index].config(state='normal') self.plusDelay[index].config(state='normal') self.adv[index].config(state='normal') self.seconds[index].set(interval[0]) self.seconds[index + 8].set(interval[1]) def add(self, number): if self.seconds[number].get() < 99: self.seconds[number].set(self.seconds[number].get() + 1) def subtract(self, number): if self.seconds[number].get() > 0: self.seconds[number].set(self.seconds[number].get() - 1)
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 = CFG(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 += _read_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 = CFG(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 simrGUI: def __init__(self): #ROOT WINDOW self.myRoot = Tk() self.myRoot.minsize(640, 480) #self.myRoot.iconbitmap(default=ICON_PATH)#utilize blank icon to cover feather self.projectName = 'New Project' #MAIN MENU self.myMenu = Menu(self.myRoot) self.myRoot.config(menu=self.myMenu) self.myRoot.title("SIMR - Scripture Indices and Ministry Resources") # File Menu self.fileMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="File", menu=self.fileMenu) self.fileMenu.add_command(label="New Project", command=self.newProject) self.fileMenu.add_command(label="Save", command=self.saveProject) self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=self.exitApp) # Edit Menu self.editMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Edit", menu=self.editMenu) self.editMenu.add_command( label="Undo", accelerator="Ctrl+Z", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Undo>>'), self.undoAction)) self.editMenu.add_command( label="Redo", accelerator="Ctrl+Y", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Redo>>'), self.redoAction)) #Control+Y not working for redo, it is pasting in # Read various bibles self.readMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Read", menu=self.readMenu) self.readMenu.add_command(label="KJV") self.readMenu.add_command(label="KJV w/ Strong's") self.readMenu.add_command(label="Septuagint") self.readMenu.add_command(label="Berean") # Books (Reference Books - in public domain) self.booksMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Books", menu=self.booksMenu) self.booksMenu.add_command(label="Number in Scripture") self.booksMenu.add_command(label="Witness of the Stars") self.booksMenu.add_command(label="How to Enjoy the Bible") # TWI Menu self.twiMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="TWI", menu=self.twiMenu) self.twiMenu.add_command(label="Scripture Index Abbreviations") self.twiMenu.add_command(label="STS List") # Help Menu self.helpMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Help", menu=self.helpMenu) self.helpMenu.add_command(label="Documentation", command=self.documentation) self.helpMenu.add_command(label="Credits", command=self.getCredits) self.helpMenu.add_command(label="About", command=self.getAbout) #TOOLBAR self.myToolbar = Frame(self.myRoot) #KJV Button self.kjvButton = Button(self.myToolbar, text="KJV", command=self.kjvButtonT) self.kjvButton.pack(side=LEFT, padx=2, pady=2) #KJVS Button self.kjvSButton = Button(self.myToolbar, text="KJV w/ Strong's", command=self.kjvsButtonT) self.kjvSButton.pack(side=LEFT, padx=2, pady=2) #Septuagint Button self.septButton = Button(self.myToolbar, text="Septuagint", command=self.septButtonT) self.septButton.pack(side=LEFT, padx=2, pady=2) #Berean Button self.bereanButton = Button(self.myToolbar, text="Berean", command=self.bereanButtonT) self.bereanButton.pack(side=LEFT, padx=2, pady=2) #Hebrew Button self.hebrewButton = Button(self.myToolbar, text="Hebrew", command=self.hebrewButtonT) self.hebrewButton.pack(side=LEFT, padx=2, pady=2) #Greek Button self.greekButton = Button(self.myToolbar, text="Greek", command=self.greekButtonT) self.greekButton.pack(side=LEFT, padx=2, pady=2) #Scripture Index Button self.scriptIndexButton = Button(self.myToolbar, text="Scripture Index", command=self.scriptIndexButtonT) self.scriptIndexButton.pack(side=LEFT, padx=2, pady=2) #Text Entry Box self.entryText = StringVar(self.myToolbar) #self.entryText.set("") self.searchBox = Entry(self.myToolbar, textvariable=self.entryText) self.searchBox.pack(side=LEFT, padx=2, pady=2) #Search Button self.searchButton = Button(self.myToolbar, text="Search All", command=self.searchAll) self.searchButton.pack(side=LEFT, padx=2, pady=2) self.searchBox.bind('<Return>', self.searchAll) #Clear Button self.clearButton = Button(self.myToolbar, text="[X]", command=self.clearTxt, fg="red") self.clearButton.pack(side=RIGHT, padx=2, pady=2) #Pack the Toolbar self.myToolbar.pack(side=TOP, fill=X) #STATUS BAR AT BOTTOM self.statusBar = Label(self.myRoot, text="Displays your status here...", bd=1, relief=SUNKEN, anchor=E) #try putting a function in the text part to see if you can get text to be dynamic #SEE - https://www.youtube.com/watch?v=Mhwiy8Tr6Wo&index=13&list=PLhTjy8cBISEp6lNKUO3iwbB1DKAkRwutl&t=0s self.statusBar.pack( side=BOTTOM, fill=X ) #displays this at the bottom and at the width of the window #FRAME self.myFrame = Frame(self.myRoot) self.myFrameText = '' self.myFrame.pack(fill=BOTH, expand=True) self.myFrame.update() #SCROLLBAR & TEXT WIDGET self.scrollbar = Scrollbar(self.myFrame) self.scrollbar.pack(side=RIGHT, fill=Y) self.textOut = Text(self.myFrame, wrap=WORD, undo=True, autoseparators=True, maxundo=-1) self.textOut.pack(side=LEFT, fill=BOTH, expand=1) self.scrollbar.config(command=self.textOut.yview) self.textOut.config(yscrollcommand=self.scrollbar.set) self.textOut.insert(END, self.myFrameText) self.textOut.bind("<Button-1>", self.leftClick) self.textOut.bind("<Button-2>", self.middleClick) self.textOut.bind("<Button-3>", self.rightClick) #https://www.python-course.eu/tkinter_text_widget.php #https://www.tutorialspoint.com/python/tk_text.htm # *** http://effbot.org/tkinterbook/text.htm *** THIS IS DETAILED DO NOT DELETE #RIGHT CLICK MENU self.rClickMenu = Menu(self.myFrame, tearoff=0) self.rClickMenu.add_command(label="Copy", accelerator="Ctrl+C", command=lambda: self.textOut.focus_get(). event_generate('<<Copy>>')) self.rClickMenu.add_command( label="Cut", accelerator="Ctrl+X", command=lambda: self.textOut.focus_get().event_generate('<<Cut>>')) self.rClickMenu.add_command(label="Paste", accelerator="Ctrl+V", command=lambda: self.textOut.focus_get(). event_generate('<<Paste>>')) self.rClickMenu.add_command( label="Greek", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickGreekSearch)) self.rClickMenu.add_command( label="Hebrew", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickHebrewSearch)) self.rClickMenu.add_command( label="Search All", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickSearch)) self.rClickMenu.add_command( label="Bible Dict.", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickSearch)) self.rClickMenu.add_command( label="Find Text", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickFindTxt)) self.rClickMenu.add_command(label="Clear", command=self.clearTxt) self.rClickMenu.add_command(label="Close Menu") #Text for Pop Ups self.about = """\n\n About this program: --------------------------\n This program is called SIMR, which is an abbreviation for "Scripture Indices & Ministry Resources."\n This program was put together with the python programming language, and is a compilation of the works of many, many others. Others who have spent countless hours studying & teaching the Word of God. My thanks to them for making researching God's Word so much easier for us!\n The goal of this program, is to provide a tool to easily compile resources for researching God's Word. A tool to help redeem the time as we diligently study God's Word. To 'simmer' is to be at a temperature just below the boiling point. It's to be in a state of the initial stages of development...\n I thought this fitting, as when we're researching a topic, the research we are doing is developing into something more. Such as a teaching or a research work. Not only that, but if you desire to boil over with God's Word, to heat to that point, you've got to let the Word burn within you. You need to steep in it. My believing is that this tool will help you in your endeavours as you stand for God in this day, time, and hour.\n Love in Christ, N. A. Flesher - 06/03/2018\n""" self.credits = """\n\n Credits, URL Links, & Resources Used: ------------------------------------------------\n Strong's Numbers & Definitions - viz.bible\n The Holy Bible, Berean Study Bible, BSB Copyright ©2016 by Bible Hub Used by Permission. All Rights Reserved Worldwide. http://berean.bible - Berean Bible Homepage\n Data for maps and coordinate locations are from OpenBible.info licensed under a Creative Commons Attribution license.\n The King James Version, Septuagint, and Strong's Concordance, as well Ethelbert W. Bullinger's books utilized in this program: The Witness of the Stars, Number in Scripture, and How to Enjoy the Bible, are all in the public domain.\n Thanks to various Christian believers from different walks of life, for their typing of the various works, for their help in gathering resources, and their advice.\n And thanks to YOU, for studying and speaking God's Word! YOU ARE GOD'S BEST!!! \n\n""" #MAIN LOOP FOR TKINTER self.myRoot.mainloop() # if you save this as .pyw then you can double click the icon and the # python console window will be hidden # ///////////////////////////////////////////////////////////////////// # METHODS OF THE SIMRGUI CLASS # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ #----------------------------------------------------------------------- # Search Methods #----------------------------------------------------------------------- # WRITE A FUNCTION TO SEARCH FOR WORD OR PHRASE TYPED OR SELECTED (RIGHT CLICK MENU) # AND RETURN LIST OF VERSES CONTAINING THE SEARCH STRING def find_txt(self, text): returnedVerses = [ i for i in scriptures_lst if text.upper() in i[1].upper() ] # THIS IS RETURNING A LIST OF LISTS OF ALL MATCHES (NESTED LIST) return returnedVerses #CURRENTLY ONLY SETUP TO SEARCH THE KJV # Search KJV verse def kjv_search( self, verse ): #CAN SEARCH FOR A LIST OF VERSES TYPED LIKE JOHN 1:1, aCTS 2:4, james 1:1 returnedVerses = [] verses = verse.split(',') for v in verses: v = v.strip() found = next(i for i in scriptures_lst if v in i) returnedVerses.append(' '.join(found)) return returnedVerses # Search KJV w/ Strong's verse #Old Testament def kjvstrnumOT_search(self, searchOT_ks): found_snOT = next(i for i in OT_sn if searchOT_ks in i) return found_snOT #New Testament def kjvstrnumNT_search(self, searchNT_ks): found_snNT = next(i for i in NT_sn if searchNT_ks in i) return found_snNT # Search for Berean verses def berean_search(self, berean_inp): if berean_inp in berean: bi = berean.index( berean_inp) # This is based on verse seached for. # Sets bi to the index of verse searched for return bi # Search through TWI scripture index def twi_scripture_index(self, twi_inp): found2 = next(i for i in twi_index if twi_inp in i) return found2 # Search through septuagint def septuagint_search(self, sept_inp): found3 = next(i for i in septuagint_lst3 if sept_inp in i) return found3 # Search for Strong's defintion def strongs_search(self, strongsNumber): if strongsNumber in strongscsvlst: sc = strongscsvlst.index( strongsNumber) # This is based on verse seached for. # Sets sc to the strongs number searched for return sc # OT Hebrew Strong's Definitions Search def strnumOT(self, OTsearch): # OT Strongs Search # This finds all <strongs numbers> on all lines printing result without <> OTstring = ''.join(OTsearch) sn_listOT = re.findall('\<(\d+)\>', OTstring) # print(sn_listOT) strongsNumberHebrew = [] for items in sn_listOT: hebrew = 'H' + items strongsNumberHebrew.append(hebrew) # print(hebrew) return strongsNumberHebrew def get_strongsHebrewDefs( self, strongsNumberHebrew ): #THIS DEFINITION PULLS ALL THE HEBREW DEFINITIONS FOR A VERSE scH_lst = [] for item in strongsNumberHebrew: if item in strongscsvlst: sc = strongscsvlst.index( item) # This is based on verse seached for. # Sets sc to the strongs number searched for sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] scH = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6 + '\n') if scH not in scH_lst: scH_lst.append(scH) return scH_lst # NT Greek Strong's Definitions Search def strnumNT(self, NTsearch): # NT Strongs Search # This finds all <strongs numbers> on all lines printing result without <> NTstring = ''.join(NTsearch) sn_listNT = re.findall('\<(\d+)\>', NTstring) # print(sn_listNT) strongsNumberGreek = [] for items in sn_listNT: greek = 'G' + items strongsNumberGreek.append(greek) # print(greek) return strongsNumberGreek def get_strongsGreekDefs( self, strongsNumberGreek ): #THIS DEFINITION PULLS ALL THE GREEK DEFINITIONS FOR A VERSE scG_lst = [] for item in strongsNumberGreek: if item in strongscsvlst: sc = strongscsvlst.index( item) # This is based on verse seached for. # Sets sc to the strongs number searched for sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] scG = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6 + '\n') if scG not in scG_lst: scG_lst.append(scG) return scG_lst #----------------------------------------------------------------------- # MENU METHODS #----------------------------------------------------------------------- # METHOD FOR TESTING PURPOSES def showIt(self): print("This button works...") # NEW PROJECT def newProject(self): print("New Project...") self.statusBar['text'] = "Starting new project..." # SAVE PROJECT def saveProject(self): with open("NewProject.txt", "w", encoding='utf-8') as txtFile: txtFile.write(self.getAllText()) print("Saving...") self.statusBar['text'] = "Saving..." #NEED TO ADD A POPUP WINDOW THAT ASKS FOR FILE NAME AND FILEPATH LOCATION TO SAVE THE FILE #FIX ENCODING - SEE OLD SIMR PROGRAM FOR ENCODINGS TO COPY OVER FOR WRITING TO TEXT FILE # EXIT APP def exitApp(self): print("Exiting...") self.statusBar['text'] = "Exiting..." exit() # REDO - FOR UPDATING STATUS BAR ONLY def redoAction(self): print("Redoing...") self.statusBar['text'] = "Redoing previous action..." # UNDO - FOR UPDATING STATUS BAR ONLY def undoAction(self): print("Undoing...") self.statusBar['text'] = "Undoing last action..." # GET DOCUMENTATION def documentation(self): print("Getting documentation...") self.statusBar['text'] = "Getting documentation..." # GET KJV def kjv(self): print("Getting King James Version...") self.statusBar['text'] = "Getting the King James Version text..." # GET KJVS def kjvs(self): print("Getting King James Version with Strong's...") self.statusBar[ 'text'] = "Getting the King James Version text with Strong's Numbers..." # GET SEPTUAGINT def sept(self): print("Getting Septuagint...") self.statusBar['text'] = "Getting the Septuagint text..." # GET BEREAN def berean(self): print("Getting Berean...") self.statusBar['text'] = "Getting the Berean texts..." # GET SCRIPTURE INDEX def scriptIndex(self): print("Getting Scripture Index...") self.statusBar[ 'text'] = "Getting The Way International resources scripture index..." # GET ABOUT INFO def getAbout(self): #Mbox('About', self.about, 0)# only works in windows self.messBox('About', self.about) self.statusBar['text'] = "Getting about information..." # GET CREDITS INFO def getCredits(self): #Mbox('Credits', self.credits, 0)# only works in windows self.messBox('Credits', self.credits) self.statusBar['text'] = "Getting credits..." #Message box def messBox(self, title, message): top = Toplevel() top.title(title) msg = Message(top, text=message) msg.pack() button = Button(top, text="OK", command=top.destroy) button.pack() #----------------------------------------------------------------------- # TOOLBAR METHODS #----------------------------------------------------------------------- #search button on toolbar def searchAll( self, event=None ): #ONLY WORKS WHEN SEARCHING FOR ONE VERSE AT A TIME BECAUSE ONLY KJV IS SET UP TO SEARCH FOR LIST OF VERSES SEPARATED BY A COMMA searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Gathering all resources for you..." #GET KJV kjv = self.kjv_search(searchText) kjvLabel = "KJV:\n" + '\n\n'.join(kjv) #GET KJV W/STRONGS try: kjvs = self.kjvstrnumOT_search(searchText) except: kjvs = self.kjvstrnumNT_search(searchText) kjvsLabel = "KJV w/Strong's - " + ' - '.join(kjvs) #GET SEPTUAGINT try: sept = self.septuagint_search(searchText) septLabel = "Septuagint - " + ' - '.join(sept) except: sept = "No verse found in Septuagint for your search..." septLabel = "Septuagint - " + sept #ISSUES WITH SEPTUAGINT TRY GENESIS 1:1 ALSO SOME JEREMIAH VERSES FOR EXAMPLE - LOOK INTO JSON FILE - # json showing first index as "\ufeffGenesis 1:1" - that's the issue #berean = self. #bereanLabel = #GET TWI SCRIPTURE INDEX try: twi = self.twi_scripture_index(searchText) twiLabel = "Scripture Index : \n" + ' '.join(twi) except: twiLabel = "Nothing found in Scripture Index for your search..." #GET ALL GREEK AND HEBREW DEFINITIONS HERE... try: ots = self.kjvstrnumOT_search(searchText) ots1 = self.strnumOT(ots) ots2 = self.get_strongsHebrewDefs(ots1) strongsDefinitions = ''.join(ots2) except: nts = self.kjvstrnumNT_search(searchText) nts1 = self.strnumNT(nts) nts2 = self.get_strongsGreekDefs(nts1) strongsDefinitions = ''.join(nts2) self.update_textOut(kjvLabel + '\n\n' + kjvsLabel + '\n\n' + strongsDefinitions + '\n\n' + septLabel + '\n\n' + twiLabel) #self.statusBar['text'] = "Ready..." #FOR KJV BUTTON def kjvButtonT( self, event=None ): #CAN NOW SEARCH FOR MORE THAN ONE VERSE WHEN VERSES ARE SEPARATED BY A COMMA print("Getting King James Version...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting KJV..." try: txt = self.kjv_search(searchText) self.update_textOut("KJV:\n" + '\n\n'.join(txt)) print(txt) return "KJV:\n" + '\n\n'.join(txt) except: self.update_textOut( "No verse found in the King James Version for your search.") #self.statusBar['text'] = "Ready..." #FOR KJV W/STRONGS BUTTON def kjvsButtonT(self, event=None): print("Getting King James Version with Strong's...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting KJV w/Strong's Numbers..." try: ot = self.kjvstrnumOT_search(searchText) self.update_textOut("KJV w/ Strong's - " + ' - '.join(ot)) print(ot) return "KJV w/ Strong's - " + ' - '.join(ot) except: nt = self.kjvstrnumNT_search(searchText) self.update_textOut("KJV w/ Strong's - " + ' - '.join(nt)) print(nt) return "KJV w/ Strong's - " + ' - '.join(nt) #self.statusBar['text'] = "Ready..." #FOR SEPTUAGINT BUTTON def septButtonT(self, event=None): print("Getting Septuagint...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Septuagint..." try: txt = self.septuagint_search(searchText) self.update_textOut("Septuagint - " + ' - '.join(txt)) print(txt) return "Septuagint - " + ' - '.join(txt) except: txt = "No verse found in Septuagint for your search." self.update_textOut("Septuagint - " + txt) print(txt) return "Septuagint - " + txt #self.statusBar['text'] = "Ready..." #FOR BEREAN BUTTON def bereanButtonT(self, event=None): print("Getting Berean...") self.statusBar['text'] = "Getting Berean Bible..." # searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Berean Bible..." # txt = # self.update_textOut(searchText) # print("Berean - " + searchText) #self.statusBar['text'] = "Ready..." #FOR SCRIPTURE INDEX BUTTON def scriptIndexButtonT(self, event=None): print("Getting Scripture Index...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar[ 'text'] = "Getting The Way International resources scripture index..." try: txt = self.twi_scripture_index(searchText) self.update_textOut("Scripture Index : \n" + ' '.join(txt)) print(txt) except: self.update_textOut( "No verse found in Scripture index for your search.") #self.statusBar['text'] = "Ready..." #FOR HEBREW BUTTON def hebrewButtonT(self, event=None): print("Getting Hebrew definitions...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Strong's Hebrew definition..." try: sc = self.strongs_search(searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] txt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) self.update_textOut(txt) print(txt) except: self.update_textOut("No Hebrew definitions found for your search.") #self.statusBar['text'] = "Ready..." #FOR GREEK BUTTON def greekButtonT(self, event=None): print("Getting Greek definitions...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Strong's Greek definition..." try: sc = self.strongs_search(searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] txt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) self.update_textOut(txt) print(txt) except: self.update_textOut("No Greek defintions found for your search.") #self.statusBar['text'] = "Ready..." #NEED TO MAKE A FUNCTION TO SEARCH FOR GREEK WORDS BY GREEK CHARACTERS YOU CAN COPY AND PASTE FROM STRONGS #ALSO ONE FOR HEBREW #NEED TO ADD A SEARCH FUNCTION TO PULL ALL GREEK DEFINITIONS IN WHEN YOU HIT GREEK BUTTON WITH A VERSE TYPED IN #NEED TO ADD A SEARCH FUNCTION TO PULL ALL HEBREW DEFINITIONS IN WHEN YOU HIT GREEK BUTTON WITH A VERSE TYPED IN #----------------------------------------------------------------------- #HANDLE MOUSE EVENTS METHODS #----------------------------------------------------------------------- #RIGHT CLICK SEARCH ALL FUNTION - TO SEARCH FOR ALL INFORMATION ABOUT SELECTED VERSE REFERENCE TEXT def rightClickSearch(self, event=None): searchText = self.textOut.clipboard_get().title().strip() self.statusBar['text'] = "Gathering all resources for you..." #GET KJV try: kjv = self.kjv_search(searchText) kjvLabel = "KJV:\n" + '\n\n'.join(kjv) except: pass #GET KJV W/STRONGS try: try: kjvs = self.kjvstrnumOT_search(searchText) except: kjvs = self.kjvstrnumNT_search(searchText) kjvsLabel = "KJV w/Strong's - " + ' - '.join(kjvs) except: pass #GET SEPTUAGINT try: try: sept = self.septuagint_search(searchText) septLabel = "Septuagint - " + ' - '.join(sept) except: sept = "No verse found in Septuagint for your search..." septLabel = "Septuagint - " + sept #ISSUES WITH SEPTUAGINT TRY GENESIS 1:1 ALSO SOME JEREMIAH VERSES FOR EXAMPLE - LOOK INTO JSON FILE - # json showing first index as "\ufeffGenesis 1:1" - that's the issue except: pass #berean = self. #bereanLabel = #GET TWI SCRIPTURE INDEX try: try: twi = self.twi_scripture_index(searchText) twiLabel = "Scripture Index : \n" + ' '.join(twi) except: twiLabel = "Nothing found in Scripture Index for your search..." except: pass try: #GET ALL GREEK AND HEBREW DEFINITIONS HERE... try: ots = self.kjvstrnumOT_search(searchText) ots1 = self.strnumOT(ots) ots2 = self.get_strongsHebrewDefs(ots1) strongsDefinitions = ''.join(ots2) except: nts = self.kjvstrnumNT_search(searchText) nts1 = self.strnumNT(nts) nts2 = self.get_strongsGreekDefs(nts1) strongsDefinitions = ''.join(nts2) except: pass #NEED TO THINK THIS THROUGH BETTER (BELOW TRY/EXCEPT NESTED TRY/EXCEPT) - MAY NEED TO USE IF ELIF ELSE STATEMENT TO DETERMINE WHICH #self.update_textOut() HAPPENS. BECAUSE THIS IS PULLING HEBREW, WHICH SHOULD PULL GREEK FIRST...??? #That is because of (see lines 721 to 733 above) H# being generated skipping the except statement to generate a G# try: self.update_textOut(kjvLabel + '\n\n' + kjvsLabel + '\n\n' + strongsDefinitions + '\n\n' + septLabel + '\n\n' + twiLabel) except: pass #self.statusBar['text'] = "Ready..." # RIGHT CLICK SEARCH FOR GREEK DEFINITION OF SELECTED TEXT NUMBER def rightClickGreekSearch(self, event=None): searchText = self.textOut.clipboard_get().title() self.statusBar['text'] = "Getting Greek word and definition for you..." try: sc = self.strongs_search('G' + searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] gTxt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) print(gTxt) self.update_textOut(gTxt) except: pass #self.statusBar['text'] = "Ready..." # RIGHT CLICK SEARCH FOR HEBREW DEFINITION OF SELECTED TEXT NUMBER def rightClickHebrewSearch(self, event=None): searchText = self.textOut.clipboard_get().title() self.statusBar[ 'text'] = "Getting Hebrew word and definition for you..." try: sc = self.strongs_search('H' + searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] hTxt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) print(hTxt) self.update_textOut(hTxt) except: pass #self.statusBar['text'] = "Ready..." def rightClickFindTxt(self, event=None): #THIS IS NOT WORKING THE WAY I WANT self.statusBar['text'] = "Searching for text phrase..." searchText = self.textOut.clipboard_get().title().strip() returnedVerses = self.find_txt(searchText) tCount = 0 for r in returnedVerses: tCount += 1 combinedVerses = [ item for sublist in returnedVerses for item in sublist ] # combine nested lists into a single list #print("combinedVerses") #print(combinedVerses) cv = [] for count, i in enumerate( combinedVerses ): # Add the " - " between the verse reference & scripture if count % 2 == 1: cv.append(i) else: cv.append(i + " - ") cVerses = [x + y for x, y in zip(cv[0::2], cv[1::2])] #combines slices #every 2 steps starting with index 0, with every 2 steps starting with index 1 #print("cv:\n") #print(cv) self.update_textOut('Total KJV verses with translated usages of "*' + searchText.lower() + '*": ' + str(tCount) + '\n' + '\n'.join(cVerses)) #self.statusBar['text'] = "Ready..." def leftClick(self, event): print("Left") #make selection here, etc def middleClick(self, event): print("Middle") def rightClick(self, event): print("Right") self.rClickMenu.post(event.x_root, event.y_root) #----------------------------------------------------------------------- #TEXT WIDGET METHODS #----------------------------------------------------------------------- # UPDATES THE TEXT ON THE TEXT WIDGET - should probably rename myFrameText to myTextOutText or something def update_textOut(self, text): self.myFrameText = text + '\n\n' self.textOut.insert(END, self.myFrameText) # NEED A METHOD TO CLEAR ALL TEXT def clearTxt(self): self.statusBar['text'] = "Clearing all text..." self.textOut.delete(1.0, END) #self.statusBar['text'] = "Ready..." # COLLECTS ALL TEXT IN THE TEXT WIDGET TO A VARIABLE - USED TO SAVE FILE def getAllText(self): contents = self.textOut.get("1.0", "end-1c") print("Getting all text...") return contents
class Application(object): def __init__(self): self.root = Tk() self.root.geometry("800x600") # GUI Title self.root.title("Beta 5.0") # Application Icon / change path after completing the application self.root.iconbitmap( r"C:\Users\vishaljs\Desktop\MY\Python\text Editor\image.jpg") #Adding scroll bar self.scroll_bar = Scrollbar(self.root, bd=1, bg='#75787A', orient=VERTICAL, cursor='arrow', relief=FLAT, activebackground='#75787A') self.scroll_bar.pack(side=RIGHT, fill=Y) # # Text Area for typing self.fontfamily = 'calibri' self.fontsize = 12 self.text_area = Text(self.root) self.text_area.pack(expand=True, fill=BOTH) self.text_area.config( font=(f"self.fontfamily", self.fontsize), foreground="#F6F3F1", background="#363636", insertbackground="white", # cursor selectforeground="#17202A", # selection selectbackground="#E5E7E9", wrap="word", yscrollcommand=self.scroll_bar.set) # Highlighting bad words self.text_area.tag_config( "badWordHighlight", #underline = True, foreground='#FCD03B', font=(f"{self.fontfamily}", self.fontsize)) #Allow scrolling with mouse movement self.scroll_bar.config(command=self.text_area.yview) self.status_bar = Label( self.root, text=f'Line 0, Column 0; ', # bg='#75787A', relief=FLAT, bd=1, anchor=E) self.status_bar.pack(side=BOTTOM, fill=X) #building application menu self.menu() #building event handlers self.events() def menu(self): # Main menu bar at the top menu = Menu(self.root) self.root.config(menu=menu) # File menu inside main menu file_menu = Menu(menu, bd=1, relief=FLAT, tearoff=0) file_menu.add_command(label='New Ctrl+N', command=partial(self.newFile, None)) file_menu.add_command( label='Open Ctrl+O', command=partial(self.openFile, None)) #partial(self.open_file, self.text_area) file_menu.add_command(label='Save Ctrl+S', command=partial(self.saveFile, None)) file_menu.add_command(label='Save as Ctrl+Shft+S', command=partial(self.saveAs, None)) # file_menu.add_separator() file_menu.add_command(label='Exit Esc', command=partial(self.quitApp, None)) # Edit menu inside main menu tools_menu = Menu(menu, bd=1, relief=FLAT, tearoff=0) tools_menu.add_command(label='Spell check', command=self.spellCheck) #view menu view_menu = Menu(menu, bd=1, relief=FLAT, tearoff=0) theme_menu = Menu(menu, bd=1, relief=FLAT, tearoff=0) theme_menu.add_command(label='Light', command=partial(self.themeChange, 'light')) theme_menu.add_command(label='Dark', command=partial(self.themeChange, 'dark')) view_menu.add_cascade(label='Theme', menu=theme_menu) # fonts menu inside View menu edit_font = Menu(menu, bd=1, relief=FLAT, tearoff=0) edit_font.add_command(label='Calibri', command=partial(self.fontChange, "Calibri", False)) edit_font.add_command(label='Arial', command=partial(self.fontChange, "Arial", False)) edit_font.add_command(label='Georgia', command=partial(self.fontChange, "Georgia", False)) edit_font.add_command(label='Times New Roman', command=partial(self.fontChange, "TimesNewRoman", False)) edit_font.add_command(label='Verdana', command=partial(self.fontChange, "Verdana", False)) edit_fontsize = Menu(menu, bd=1, relief=FLAT, tearoff=0) for x in range(6, 26, 2): edit_fontsize.add_command(label=f'{x}', command=partial(self.fontChange, False, f"{x}")) # adding font meinu to style view_menu.add_cascade(label='Font Family', menu=edit_font) view_menu.add_cascade(label='Font Size', menu=edit_fontsize) # Help Menu inside main menu self.help_menu = Menu(menu, bd=1, relief=FLAT, tearoff=0) #adding all sub-menu to main menu.add_cascade(label='File', menu=file_menu) menu.add_cascade(label='View', menu=view_menu) menu.add_cascade(label='Tools', menu=tools_menu) menu.add_cascade( label="Credit", command=lambda: webbrowser.open( "https://www.linkedin.com/in/vishaljeet-singh-2b6099128/")) def events(self): #file control events - shortcuts self.text_area.bind("<Control-O>", self.openFile) self.text_area.bind("<Control-N>", self.newFile) self.text_area.bind("<Control-S>", self.saveFile) self.text_area.bind("<Control-o>", self.openFile) self.text_area.bind("<Control-n>", self.newFile) self.text_area.bind("<Control-s>", self.saveFile) self.text_area.bind("<Control-Shift-S>", self.saveAs) self.text_area.bind("<Control-Shift-s>", self.saveAs) self.text_area.bind("<Escape>", self.quitApp) # spell check events self.text_area.bind("<space>", self.spellCheckCursor) self.text_area.bind("<Left>", self.spellCheckCursor) self.text_area.bind("<Right>", self.spellCheckCursor) self.text_area.bind("<Return>", self.spellCheckCursor) # suggestions events self.text_area.bind("<Button-3>", self.suggestions) self.text_area.bind("<Control-Tab>", self.suggestions) for cat in [ascii_letters, digits]: for alp in cat: self.text_area.bind(f"{alp}", self.statusbarUpdate) for alp in [ "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "minus", "period", "slash", "colon", "semicolon", "less", "equal", "greater", "question", "at", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "braceleft", "bar", "braceright", "asciitilde", "nobreakspace", "exclamdown", "cent", "sterling", "currency", "yen", "brokenbar", "section", "diaeresis", "copyright", "ordfeminine", "guillemotleft", "notsign", "hyphen", "registered", "macron", "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu", "paragraph", "periodcentered", "cedilla", "onesuperior", "masculine", "guillemotright", "onequarter", "onehalf", "threequarters", "questiondown", "Agrave", "Aacute", "Acircumflex", "Atilde", "Adiaeresis", "Aring", "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex", "Ediaeresis", "Igrave", "Iacute", "Icircumflex", "Idiaeresis", "Eth", "Ntilde", "Ograve", "Oacute", "Ocircumflex", "Otilde", "Odiaeresis", "multiply", "Ooblique", "Ugrave", "Uacute", "Ucircumflex", "Udiaeresis", "Yacute", "Thorn", "ssharp", "agrave", "aacute", "acircumflex", "atilde", "adiaeresis", "aring", "ae", "ccedilla", "egrave", "eacute", "ecircumflex", "ediaeresis", "igrave", "iacute", "icircumflex", "idiaeresis", "eth", "ntilde", "ograve", "oacute", "ocircumflex", "otilde", "odiaeresis", "division", "oslash", "ugrave", "uacute", "ucircumflex", "udiaeresis", "yacute", "thorn", "ydiaeresis", "Aogonek", "breve", "Lstroke", "Lcaron", "Sacute", "Scaron", "Scedilla", "Tcaron", "Zacute", "Zcaron", "Zabovedot", "aogonek", "ogonek", "lstroke", "lcaron", "sacute", "caron", "scaron", "scedilla", "tcaron", "zacute", "doubleacute", "zcaron", "zabovedot", "Racute", "Abreve", "Cacute", "Ccaron", "Eogonek", "Ecaron", "Dcaron", "Nacute", "Ncaron", "Odoubleacute", "Rcaron", "Uring", "Udoubleacute", "Tcedilla", "racute", "abreve", "cacute", "ccaron", "eogonek", "ecaron", "dcaron", "nacute", "ncaron", "odoubleacute", "rcaron", "uring", "udoubleacute", "tcedilla", "abovedot", "Hstroke", "Hcircumflex", "Iabovedot", "Gbreve", "Jcircumflex", "hstroke", "hcircumflex", "idotless", "gbreve", "jcircumflex", "Cabovedot", "Ccircumflex", "Gabovedot", "Gcircumflex", "Ubreve", "Scircumflex", "cabovedot", "ccircumflex", "gabovedot", "gcircumflex", "ubreve", "scircumflex", "kappa", "Rcedilla", "Itilde", "Lcedilla", "Emacron", "Gcedilla", "Tslash", "rcedilla", "itilde", "lcedilla", "emacron", "gacute", "tslash", "ENG", "eng", "Amacron", "Iogonek", "Eabovedot", "Imacron", "Ncedilla", "Omacron", "Kcedilla", "Uogonek", "Utilde", "Umacron", "amacron", "iogonek", "eabovedot", "imacron", "ncedilla", "omacron", "kcedilla", "uogonek", "utilde", "umacron", "overline", "kana_fullstop", "kana_openingbracket", "kana_closingbracket", "kana_comma", "kana_middledot", "kana_WO", "kana_a", "kana_i", "kana_u", "kana_e", "kana_o", "kana_ya", "kana_yu", "kana_yo", "kana_tu", "prolongedsound", "kana_A", "kana_I", "kana_U", "kana_E", "kana_O", "kana_KA", "kana_KI", "kana_KU", "kana_KE", "kana_KO", "kana_SA", "kana_SHI", "kana_SU", "kana_SE", "kana_SO", "kana_TA", "kana_TI", "kana_TU", "kana_TE", "kana_TO", "kana_NA", "kana_NI", "kana_NU", "kana_NE", "kana_NO", "kana_HA", "kana_HI", "kana_HU", "kana_HE", "kana_HO", "kana_MA", "kana_MI", "kana_MU", "kana_ME", "kana_MO", "kana_YA", "kana_YU", "kana_YO", "kana_RA", "kana_RI", "kana_RU", "kana_RE", "kana_RO", "kana_WA", "kana_N", "voicedsound", "semivoicedsound", "Arabic_comma", "Arabic_semicolon", "Arabic_question_mark", "Arabic_hamza", "Arabic_maddaonalef", "Arabic_hamzaonalef", "Arabic_hamzaonwaw", "Arabic_hamzaunderalef", "Arabic_hamzaonyeh", "Arabic_alef", "Arabic_beh", "Arabic_tehmarbuta", "Arabic_teh", "Arabic_theh", "Arabic_jeem", "Arabic_hah", "Arabic_khah", "Arabic_dal", "Arabic_thal", "Arabic_ra", "Arabic_zain", "Arabic_seen", "Arabic_sheen", "Arabic_sad", "Arabic_dad", "Arabic_tah", "Arabic_zah", "Arabic_ain", "Arabic_ghain", "Arabic_tatweel", "Arabic_feh", "Arabic_qaf", "Arabic_kaf", "Arabic_lam", "Arabic_meem", "Arabic_noon", "Arabic_heh", "Arabic_waw", "Arabic_alefmaksura", "Arabic_yeh", "Arabic_fathatan", "Arabic_dammatan", "Arabic_kasratan", "Arabic_fatha", "Arabic_damma", "Arabic_kasra", "Arabic_shadda", "Arabic_sukun", "Serbian_dje", "Macedonia_gje", "Cyrillic_io", "Ukranian_je", "Macedonia_dse", "Ukranian_i", "Ukranian_yi", "Serbian_je", "Serbian_lje", "Serbian_nje", "Serbian_tshe", "Macedonia_kje", "Byelorussian_shortu", "Serbian_dze", "numerosign", "Serbian_DJE", "Macedonia_GJE", "Cyrillic_IO", "Ukranian_JE", "Macedonia_DSE", "Ukranian_I", "Ukranian_YI", "Serbian_JE", "Serbian_LJE", "Serbian_NJE", "Serbian_TSHE", "Macedonia_KJE", "Byelorussian_SHORTU", "Serbian_DZE", "Cyrillic_yu", "Cyrillic_a", "Cyrillic_be", "Cyrillic_tse", "Cyrillic_de", "Cyrillic_ie", "Cyrillic_ef", "Cyrillic_ghe", "Cyrillic_ha", "Cyrillic_i", "Cyrillic_shorti", "Cyrillic_ka", "Cyrillic_el", "Cyrillic_em", "Cyrillic_en", "Cyrillic_o", "Cyrillic_pe", "Cyrillic_ya", "Cyrillic_er", "Cyrillic_es", "Cyrillic_te", "Cyrillic_u", "Cyrillic_zhe", "Cyrillic_ve", "Cyrillic_softsign", "Cyrillic_yeru", "Cyrillic_ze", "Cyrillic_sha", "Cyrillic_e", "Cyrillic_shcha", "Cyrillic_che", "Cyrillic_hardsign", "Cyrillic_YU", "Cyrillic_A", "Cyrillic_BE", "Cyrillic_TSE", "Cyrillic_DE", "Cyrillic_IE", "Cyrillic_EF", "Cyrillic_GHE", "Cyrillic_HA", "Cyrillic_I", "Cyrillic_SHORTI", "Cyrillic_KA", "Cyrillic_EL", "Cyrillic_EM", "Cyrillic_EN", "Cyrillic_O", "Cyrillic_PE", "Cyrillic_YA", "Cyrillic_ER", "Cyrillic_ES", "Cyrillic_TE", "Cyrillic_U", "Cyrillic_ZHE", "Cyrillic_VE", "Cyrillic_SOFTSIGN", "Cyrillic_YERU", "Cyrillic_ZE", "Cyrillic_SHA", "Cyrillic_E", "Cyrillic_SHCHA", "Cyrillic_CHE", "Cyrillic_HARDSIGN", "Greek_ALPHAaccent", "Greek_EPSILONaccent", "Greek_ETAaccent", "Greek_IOTAaccent", "Greek_IOTAdiaeresis", "Greek_IOTAaccentdiaeresis", "Greek_OMICRONaccent", "Greek_UPSILONaccent", "Greek_UPSILONdieresis", "Greek_UPSILONaccentdieresis", "Greek_OMEGAaccent", "Greek_alphaaccent", "Greek_epsilonaccent", "Greek_etaaccent", "Greek_iotaaccent", "Greek_iotadieresis", "Greek_iotaaccentdieresis", "Greek_omicronaccent", "Greek_upsilonaccent", "Greek_upsilondieresis", "Greek_upsilonaccentdieresis", "Greek_omegaaccent", "Greek_ALPHA", "Greek_BETA", "Greek_GAMMA", "Greek_DELTA", "Greek_EPSILON", "Greek_ZETA", "Greek_ETA", "Greek_THETA", "Greek_IOTA", "Greek_KAPPA", "Greek_LAMBDA", "Greek_MU", "Greek_NU", "Greek_XI", "Greek_OMICRON", "Greek_PI", "Greek_RHO", "Greek_SIGMA", "Greek_TAU", "Greek_UPSILON", "Greek_PHI", "Greek_CHI", "Greek_PSI", "Greek_OMEGA", "Greek_alpha", "Greek_beta", "Greek_gamma", "Greek_delta", "Greek_epsilon", "Greek_zeta", "Greek_eta", "Greek_theta", "Greek_iota", "Greek_kappa", "Greek_lambda", "Greek_mu", "Greek_nu", "Greek_xi", "Greek_omicron", "Greek_pi", "Greek_rho", "Greek_sigma", "Greek_finalsmallsigma", "Greek_tau", "Greek_upsilon", "Greek_phi", "Greek_chi", "Greek_psi", "Greek_omega", "leftradical", "topleftradical", "horizconnector", "topintegral", "botintegral", "vertconnector", "topleftsqbracket", "botleftsqbracket", "toprightsqbracket", "botrightsqbracket", "topleftparens", "botleftparens", "toprightparens", "botrightparens", "leftmiddlecurlybrace", "rightmiddlecurlybrace", "topleftsummation", "botleftsummation", "topvertsummationconnector", "botvertsummationconnector", "toprightsummation", "botrightsummation", "rightmiddlesummation", "lessthanequal", "notequal", "greaterthanequal", "integral", "therefore", "variation", "infinity", "nabla", "approximate", "similarequal", "ifonlyif", "implies", "identical", "radical", "includedin", "includes", "intersection", "union", "logicaland", "logicalor", "partialderivative", "function", "leftarrow", "uparrow", "rightarrow", "downarrow", "blank", "soliddiamond", "checkerboard", "ht", "ff", "cr", "lf", "nl", "vt", "lowrightcorner", "uprightcorner", "upleftcorner", "lowleftcorner", "crossinglines", "horizlinescan1", "horizlinescan3", "horizlinescan5", "horizlinescan7", "horizlinescan9", "leftt", "rightt", "bott", "topt", "vertbar", "emspace", "enspace", "em3space", "em4space", "digitspace", "punctspace", "thinspace", "hairspace", "emdash", "endash", "signifblank", "ellipsis", "doubbaselinedot", "onethird", "twothirds", "onefifth", "twofifths", "threefifths", "fourfifths", "onesixth", "fivesixths", "careof", "figdash", "leftanglebracket", "decimalpoint", "rightanglebracket", "marker", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "trademark", "signaturemark", "trademarkincircle", "leftopentriangle", "rightopentriangle", "emopencircle", "emopenrectangle", "leftsinglequotemark", "rightsinglequotemark", "leftdoublequotemark", "rightdoublequotemark", "prescription", "minutes", "seconds", "latincross", "hexagram", "filledrectbullet", "filledlefttribullet", "filledrighttribullet", "emfilledcircle", "emfilledrect", "enopencircbullet", "enopensquarebullet", "openrectbullet", "opentribulletup", "opentribulletdown", "openstar", "enfilledcircbullet", "enfilledsqbullet", "filledtribulletup", "filledtribulletdown", "leftpointer", "rightpointer", "club", "diamond", "heart", "maltesecross", "dagger", "doubledagger", "checkmark", "ballotcross", "musicalsharp", "musicalflat", "malesymbol", "femalesymbol", "telephone", "telephonerecorder", "phonographcopyright", "caret", "singlelowquotemark", "doublelowquotemark", "cursor", "leftcaret", "rightcaret", "downcaret", "upcaret", "overbar", "downtack", "upshoe", "downstile", "underbar", "jot", "quad", "uptack", "circle", "upstile", "downshoe", "rightshoe", "leftshoe", "lefttack", "righttack", "hebrew_aleph", "hebrew_beth", "hebrew_gimmel", "hebrew_daleth", "hebrew_he", "hebrew_waw", "hebrew_zayin", "hebrew_het", "hebrew_teth", "hebrew_yod", "hebrew_finalkaph", "hebrew_kaph", "hebrew_lamed", "hebrew_finalmem", "hebrew_mem", "hebrew_finalnun", "hebrew_nun", "hebrew_samekh", "hebrew_ayin", "hebrew_finalpe", "hebrew_pe", "hebrew_finalzadi", "hebrew_zadi", "hebrew_kuf", "hebrew_resh", "hebrew_shin", "hebrew_taf", "BackSpace", "Tab", "Linefeed", "Clear", "Pause", "Scroll_Lock", "Sys_Req", "Multi_key", "Kanji", "Home", "Up", "Down", "Prior", "Next", "End", "Begin", "Win_L", "Win_R", "App", "Select", "Print", "Execute", "Insert", "Undo", "Redo", "Menu", "Find", "Cancel", "Help", "Break", "Hebrew_switch", "Num_Lock", "KP_Space", "KP_Tab", "KP_Enter", "KP_F1", "KP_F2", "KP_F3", "KP_F4", "KP_Multiply", "KP_Add", "KP_Separator", "KP_Subtract", "KP_Decimal", "KP_Divide", "KP_0", "KP_1", "KP_2", "KP_3", "KP_4", "KP_5", "KP_6", "KP_7", "KP_8", "KP_9", "KP_Equal", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "L1", "L2", "L3", "L4", "L5", "L6", "L7", "L8", "L9", "L10", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", "R12", "F33", "R14", "R15", "Shift_L", "Shift_R", "Control_L", "Control_R", "Caps_Lock", "Shift_Lock", "Meta_L", "Meta_R", "Alt_L", "Alt_R", "Super_L", "Super_R", "Hyper_L", "Hyper_R", "Delete" ]: self.text_area.bind(f"<{alp}>", self.statusbarUpdate)
class Application(threading.Thread): def __init__(self): super(Application, self).__init__() self.chaojiying = Chaojiying_Client("18612800000", "12345678", "1902") self.__createGUI() self.lock = threading.Lock() def __createGUI(self): self.root = mtk.Tk() self.root.title("宽带查询助手2.0") self.root.geometry("860x700") self.companySet = mtk.LabelFrame(text="通信公司选择", fg="blue") self.companySet.place(x=50, y=20, width=220, height=100) self.labelCompany = mtk.Label(self.companySet, text="通信公司:") self.labelCompany.place(x=20, y=20, width=60, height=25) self.boxCompany = ttk.Combobox(self.companySet) self.boxCompany.place(x=100, y=20, width=80, height=25) self.boxCompany["values"] = ["中国移动", "中国联通"] self.loadExcel = mtk.LabelFrame(text="导入Excel文件", fg="blue") self.loadExcel.place(x=320, y=20, width=220, height=100) self.fileChoose = mtk.Button( self.loadExcel, text="选择文件", command=lambda: self.thread_it(self.__loadExcel)) self.fileChoose.place(x=15, y=40, width=80, height=25) self.outExcel = mtk.Button( self.loadExcel, text="导出Excel", command=lambda: self.thread_it(self._saveExcel)) self.outExcel.place(x=120, y=40, width=80, height=25) self.staticData = mtk.Label(self.loadExcel, text="数量统计:") self.staticData.place(x=20, y=5, width=60, height=20) self.entryShowNum = mtk.Label(self.loadExcel, text="0/0") self.entryShowNum.place(x=90, y=5, width=100, height=20) self.showDataBox = mtk.LabelFrame(text="数据展示区域", fg="blue") self.showDataBox.place(x=50, y=150, width=760, height=300) title = ['1', '2', '3', '4', '5', '6', '7', '8'] self.box = ttk.Treeview(self.showDataBox, columns=title, show='headings') self.box.place(x=20, y=15, width=730, height=250) self.box.column('1', width=30, anchor='center') self.box.column('2', width=90, anchor='center') self.box.column('3', width=100, anchor='center') self.box.column('4', width=80, anchor='center') self.box.column('5', width=60, anchor='center') self.box.column('6', width=80, anchor='center') self.box.column('7', width=100, anchor='center') self.box.column('8', width=80, anchor='center') self.box.heading('1', text='序号') self.box.heading('2', text='宽带编码') self.box.heading('3', text='机主姓名') self.box.heading('4', text='产品名称') self.box.heading('5', text='签约速率') self.box.heading('6', text='联系电话') self.box.heading('7', text='装机地址') self.box.heading('8', text='到期时间') self.VScroll1 = Scrollbar(self.box, orient='vertical', command=self.box.yview) self.VScroll1.pack(side="right", fill="y") self.box.configure(yscrollcommand=self.VScroll1.set) self.btnBox = mtk.LabelFrame(text="任务栏", fg="blue") self.btnBox.place(x=590, y=20, width=220, height=100) self.btnStart = mtk.Button(self.btnBox, text="开始", command=lambda: self.thread_it(self.start)) self.btnStart.place(x=20, y=20, width=80, height=30) self.btnEnd = mtk.Button(self.btnBox, text="退出", command=lambda: self.thread_it(self.stop)) self.btnEnd.place(x=120, y=20, width=80, height=30) self.loginfo = mtk.LabelFrame(text="log日志信息", fg="blue") self.loginfo.place(x=50, y=480, width=760, height=150) self.logtext = scrolledtext.ScrolledText(self.loginfo, fg="green") self.logtext.place(x=20, y=15, width=730, height=100) def deleteTree(self): x = self.box.get_children() for item in x: self.box.delete(item) def __loadExcel(self): excelPath = filedialog.askopenfilename(title=u'选择文件') if excelPath: try: self.deleteTree() self.treeIndex = 1 self.totals = 0 self.excelData = [] self.totalData = [[ "机主姓名", "宽带编码", "产品名称", "签约速率", "联系电话", "装机地址", "到期时间" ]] wb = load_workbook(excelPath) ws = wb.active self.totals = ws.max_row - 1 self.index = ws.max_column if self.index == 2: self.excelData = [[str(i[1]), str(i[0])] for i in list(ws.values)[1:]] else: self.excelData = [[str(i[0])] for i in list(ws.values)[1:]] showinfo("提示信息", "共导入{}条数据".format(self.totals)) self.entryShowNum.configure(text=f"{0}/{self.totals}") self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t导入Excel文件成功,共计{self.totals}条数据.\n" ) self.logtext.yview_moveto(1.0) except Exception as e: print(e.args) showerror("错误信息", "请选择正确格式的Excel文件!") else: showerror("错误信息", "请导入文件!") async def __getContentFor10010(self, semaphore, userName, userCode): async with semaphore: link = f"https://openapp.10010.com/bj/kdxf/Kdxf_queryUserProductMes.action?{datetime.now().strftime('%H:%M:%S')}%20GMT+0800%20(%D6%D0%B9%FA%B1%EA%D7%BC%CA%B1%BC%E4)&query_type=1&query_value1=40&query_value2={userCode}&query_value3={userName}" headers = { 'Host': 'openapp.10010.com', 'Connection': 'keep-alive', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://openapp.10010.com/bj/kdxf/Kdxf_toKdxf.action', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9' } async with aiohttp.ClientSession(headers=headers) as session: # try: async with await session.get(link) as resp: self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userName}\t\t{userCode}\t\t正在查询客户宽带信息,请不要关闭窗口.\n" ) self.logtext.yview_moveto(1.0) content = await resp.text() print(111111, content) await asyncio.sleep(random.uniform(0, 1)) data = json.loads(content.replace("'", "\"")).get("json") return data # except Exception as e: # print(22222, e.args) # return def __getContentFor10086(self, userCode): self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userCode}\t\t正在查询客户宽带信息,请不要关闭窗口.\n" ) self.logtext.yview_moveto(1.0) link = "https://service.bj.10086.cn/poffice/renewal/mainOfRenewal.action" headers = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Host': 'service.bj.10086.cn', 'Referer': 'https://service.bj.10086.cn/poffice/renewal/mainOfRenewal.action', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36', } session = requests.Session() session.headers = headers try: session.get(link) self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userCode}\t\t正在进行识别验证码,请不要关闭窗口.\n" ) self.logtext.yview_moveto(1.0) content = session.get( "https://service.bj.10086.cn/poffice/jsp/package/bb/checkCode.jsp" ).content result = self.chaojiying.PostPic(content, 1902) captchaCode = result.get("pic_str") pic_id = result.get("pic_id") link = f"https://service.bj.10086.cn/poffice/renewal/getBBnumberByMobile.action" formData = {"BILL_ID": userCode, "verificationCode": captchaCode} captchaRes = session.post(link, data=parse.urlencode(formData)) if "erroryzm" in captchaRes.text: res = self.chaojiying.ReportError(pic_id) return elif "null" in captchaRes.text: return "<html><title>没有查到相关记录</title></html>" elif "error" in captchaRes.text: self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userCode}\t\t发现错误宽带账号.\n" ) return "<html><title>账号输入有误</title></html>" else: realBill = json.loads(captchaRes.json())[0].get("realBill") link = "https://service.bj.10086.cn/poffice/renewal/toRenewalPage.action" formData = {"billId": realBill} self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userCode}\t\t正在解析网页数据,请不要关闭窗口.\n" ) self.logtext.yview_moveto(1.0) content = session.post(link, data=parse.urlencode(formData)).text return content except Exception as e: print(e.args) return def __content10010(self, contentList, userName, userCode): treeDataList = [] if contentList: for content in contentList: try: treeData = [ self.treeIndex, content.get("serialNumber"), content.get("custName"), content.get("productName"), content.get("speed"), content.get("guhuaNumber"), content.get("installAddr"), content.get("endDate").split(" ")[0], ] treeDataList.append(treeData) except Exception as e: print(e.args) treeData = [ self.treeIndex, userCode, userName, "", "", "", "", "", ] treeDataList.append(treeData) self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userName}\t\t{userCode}\t\t获取数据成功.\n" ) self.logtext.yview_moveto(1.0) self.treeIndex += 1 return treeDataList return def __content10086(self, content, userCode): if content: html = pq(content) try: # "宽带编码", "机主姓名", "产品名称", "签约速率", "联系电话", "装机地址", "到期时间" treeData = [ self.treeIndex, userCode, html.find( "div.currinfos-cont:nth-child(2) dl:nth-child(1) dd" ).text(), html.find( "div.currinfos-cont:nth-child(2) dl:nth-child(4) dd" ).text(), "", html.find( "div.currinfos-cont:nth-child(2) dl:nth-child(3) dd"). text(), "", html.find( "div.currinfos-cont:nth-child(2) dl:nth-child(5) dd"). text(), ] except: treeData = [ self.treeIndex, "", userCode, "", "", "", "", "", ] self.logtext.insert( END, f"{datetime.now().strftime('%Y:%m:%d %H:%M:%S')}\t\t{userCode}\t\t获取数据成功.\n" ) self.logtext.yview_moveto(1.0) return treeData return def __crawler10086(self, semaphore, userCode): semaphore.acquire() _content = self.__getContentFor10086(userCode) treeData = self.__content10086(_content, userCode) if treeData: self.totalData.append(treeData[1:]) self.box.insert("", "end", values=treeData) self.entryShowNum.configure(text=f"{self.treeIndex}/{self.totals}") self.lock.acquire() self.treeIndex += 1 self.lock.release() self.excelData.remove([userCode]) self.box.yview_moveto(1.0) semaphore.release() async def __crawler10010(self, semaphore, userCode, userName): _content = await self.__getContentFor10010(semaphore, userName, userCode) treeDataList = self.__content10010(_content, userName, userCode) if treeDataList: for treeData in treeDataList: self.totalData.append(treeData[1:]) self.box.insert("", "end", values=treeData) self.entryShowNum.configure( text=f"{treeData[0]}/{self.totals}") try: self.excelData.remove([userCode, userName]) except: pass self.box.yview_moveto(1.0) def _saveExcel(self): if not self.totalData: showerror("错误信息", "当前不存在任何数据!") return excelPath = filedialog.asksaveasfilename( title=u'保存文件', filetypes=[("xlsx", ".xlsx")]) + ".xlsx" if excelPath.strip(".xlsx"): wb = Workbook() ws = wb.active for line in self.totalData: ws.append(line) wb.save(excelPath) showinfo("提示信息", "保存成功!") async def taskManager10010(self, dataList, func): tasks = [] semaphore = asyncio.Semaphore(5) for data in dataList: task = asyncio.ensure_future(func(semaphore, *data)) tasks.append(task) await asyncio.wait(tasks) def taskManager10086(self, dataList, func): semaphore = threading.Semaphore(2) ts = [ threading.Thread(target=func, args=( semaphore, usrCode[0], )) for usrCode in dataList ] [t.start() for t in ts] [t.join() for t in ts] def start(self): self.company = self.boxCompany.get() if not self.company: showerror("错误信息", "请选择通信公司!") else: if self.totals > 0: if self.company == "中国联通": new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) loop = asyncio.get_event_loop() loop.run_until_complete( self.taskManager10010(self.excelData, self.__crawler10010)) else: self.box.column('2', width=100, anchor='center') self.box.column('3', width=60, anchor='center') self.box.column('4', width=170, anchor='center') self.box.column('5', width=0, anchor='center') self.box.column('6', width=120, anchor='center') self.box.column('7', width=0, anchor='center') self.box.column('8', width=160, anchor='center') self.taskManager10086(self.excelData, self.__crawler10086) else: showerror("错误信息", "当前无用户信息!") while self.excelData: if self.company == "中国联通": loop = asyncio.get_event_loop() loop.run_until_complete( self.taskManager10010(self.excelData, self.__crawler10010)) else: self.taskManager10086(self.excelData, self.__crawler10086) showinfo("提示信息", "任务结束!") def stop(self): os._exit(0) @staticmethod def thread_it(func, *args): t = threading.Thread(target=func, args=args) t.setDaemon(True) t.start() def run(self): self.root.mainloop()
class Chatbox(object): def __init__(self, master, my_nick=None, command=None, topic=None, entry_controls=None, maximum_lines=None, timestamp_template=None, scrollbar_background=None, scrollbar_troughcolor=None, history_background=None, history_font=None, history_padx=None, history_pady=None, history_width=None, entry_font=None, entry_background=None, entry_foreground=None, label_template=u"{nick}", label_font=None, logging_file=None, tags=None): self.interior = Frame(master, class_="Chatbox") self._command = command self._is_empty = True self._maximum_lines = maximum_lines self._timestamp_template = timestamp_template self._command = command self._label_template = label_template self._logging_file = logging_file if logging_file is None: self._log = None else: try: self._log = open(logging_file, "r") except: self._log = None top_frame = Frame(self.interior, class_="Top") top_frame.pack(expand=True, fill=BOTH) self._textarea = Text(top_frame, state=DISABLED) self._vsb = Scrollbar(top_frame, takefocus=0, command=self._textarea.yview) self._vsb.pack(side=RIGHT, fill=Y) self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH) self._textarea["yscrollcommand"] = self._vsb.set entry_frame = Frame(self.interior, class_="Chatbox_Entry") entry_frame.pack(fill=X, anchor=N) if entry_controls is not None: controls_frame = Frame(entry_frame, class_="Controls") controls_frame.pack(fill=X) entry_controls(controls_frame, chatbox=self) bottom_of_entry_frame = Frame(entry_frame) self._entry_label = Label(bottom_of_entry_frame) self._entry = Entry(bottom_of_entry_frame) else: self._entry_label = Label(entry_frame) self._entry = Entry(entry_frame) self._entry.pack(side=LEFT, expand=YES, fill=X) self._entry.bind("<Return>", self._on_message_sent) self._entry.focus() if history_background: self._textarea.configure(background=history_background) if history_font: self._textarea.configure(font=history_font) if history_padx: self._textarea.configure(padx=history_padx) if history_width: self._textarea.configure(width=history_width) if history_pady: self._textarea.configure(pady=history_pady) if scrollbar_background: self._vsb.configure(background=scrollbar_background) if scrollbar_troughcolor: self._vsb.configure(troughcolor=scrollbar_troughcolor) if entry_font: self._entry.configure(font=entry_font) if entry_background: self._entry.configure(background=entry_background) if entry_foreground: self._entry.configure(foreground=entry_foreground) if label_font: self._entry_label.configure(font=label_font) if tags: for tag, tag_config in tags.items(): self._textarea.tag_config(tag, **tag_config) self.set_nick(my_nick) @property def topic(self): return @topic.setter def topic(self, topic): return def focus_entry(self): self._entry.focus() def bind_entry(self, event, handler): self._entry.bind(event, handler) def bind_textarea(self, event, handler): self._textarea.bind(event, handler) def bind_tag(self, tagName, sequence, func, add=None): self._textarea.tag_bind(tagName, sequence, func, add=add) def focus(self): self._entry.focus() def user_message(self, nick, content): if self._timestamp_template is None: self._write((u"%s:" % nick, "nick"), " ", (content, "user_message")) else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"), " ", (content, "user_message")) def notification_message(self, content, tag=None): if tag is None: tag = "notification" self._write((content, tag)) notification = notification_message def notification_of_private_message(self, content, from_, to): if self._timestamp_template is None: self.notification_message( u"{from_} -> {to}: {content}".format(from_=from_, to=to, content=content), "notification_of_private_message") else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self.notification_message( u"{timestamp} {from_} -> {to}: {content}".format( timestamp=timestamp, from_=from_, to=to, content=content), "notification_of_private_message") def new_message(self, message): if isinstance(message, User_Message): self.user_message(message.content, message.nick) elif isinstance(message, Notification_Message): self.notification(message.content, message.tag) elif isinstance(message, Notification_Of_Private_Message): self.notification_of_private_message(message.from_, message.to, message.content) else: raise Exception("Bad message") def tag(self, tag_name, **kwargs): self._textarea.tag_config(tag_name, **kwargs) def clear(self): self._is_empty = True self._textarea.delete('1.0', END) @property def logging_file(self): return self._logging_file def send(self, content): if self._my_nick is None: raise Exception("Nick not set") self.user_message(self._my_nick, content) def _filter_text(self, text): return "".join(ch for ch in text if ch <= u"\uFFFF") def _write(self, *args): if len(args) == 0: return relative_position_of_scrollbar = self._vsb.get()[1] self._textarea.config(state=NORMAL) if self._is_empty: self._is_empty = False else: self._textarea.insert(END, "\n") if self._log is not None: self._log.write("\n") for arg in args: if isinstance(arg, tuple): text, tag = arg # Parsing not allowed characters text = self._filter_text(text) self._textarea.insert(END, text, tag) else: text = arg text = self._filter_text(text) self._textarea.insert(END, text) if self._log is not None: self._log.write(text) if self._maximum_lines is not None: start_line = int(self._textarea.index('end-1c').split('.') [0]) - self._maximum_lines if lines_to_delete >= 1: self._textarea.delete('%s.0' % start_line, END) self._textarea.config(state=DISABLED) if relative_position_of_scrollbar == 1: self._textarea.yview_moveto(1) def _on_message_sent(self, event): message = self._entry.get() self._entry.delete(0, END) self.send(message) if self._command: self._command(message) def set_nick(self, my_nick): self._my_nick = my_nick if my_nick: text = self._label_template.format(nick=my_nick) self._entry_label["text"] = text self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry) else: self._entry_label.pack_forget()
class Editor(): def __init__(self, root): self.root = root self.TITLE = "Subedi Editor" self.file_path = None self.set_title() frame = Frame(root) self.yscrollbar = Scrollbar(frame, orient="vertical") self.editor = Text(frame, yscrollcommand=self.yscrollbar.set) self.editor.pack(side="left", fill="both", expand=1) self.editor.config( wrap="word", # use word wrapping undo=True, # Tk 8.4 width=80) self.editor.focus() self.yscrollbar.pack(side="right", fill="y") self.yscrollbar.config(command=self.editor.yview) frame.pack(fill="both", expand=1) #instead of closing the window, execute a function root.protocol("WM_DELETE_WINDOW", self.file_quit) #create a top level menu self.menubar = Menu(root) #Menu item File filemenu = Menu( self.menubar, tearoff=0) # tearoff = 0 => can't be seperated from window filemenu.add_command(label="New", underline=1, command=self.file_new, accelerator="Ctrl+N") filemenu.add_command(label="Open...", underline=1, command=self.file_open, accelerator="Ctrl+O") filemenu.add_command(label="Save", underline=1, command=self.file_save, accelerator="Ctrl+S") filemenu.add_command(label="Save As...", underline=5, command=self.file_save_as, accelerator="Ctrl+Alt+S") filemenu.add_command(label="Run", underline=1, command=self.file_run, accelerator="Ctrl+R") filemenu.add_separator() filemenu.add_command(label="Exit", underline=2, command=self.file_quit, accelerator="Alt+F4") self.menubar.add_cascade(label="File", underline=0, menu=filemenu) # display the menu root.config(menu=self.menubar) def save_if_modified(self, event=None): if self.editor.edit_modified(): #modified response = messagebox.askyesnocancel( "Save?", "This document has been modified. Do you want to save changes?" ) #yes = True, no = False, cancel = None if response: #yes/save result = self.file_save() if result == "saved": #saved return True else: #save cancelled return None else: return response #None = cancel/abort, False = no/discard else: #not modified return True def file_new(self, event=None): result = self.save_if_modified() if result != None: #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified self.editor.delete(1.0, "end") self.editor.edit_modified(False) self.editor.edit_reset() self.file_path = None self.set_title() def file_open(self, event=None, filepath=None): result = self.save_if_modified() if result != None: #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified if filepath == None: filepath = filedialog.askopenfilename() if filepath != None and filepath != '': with open(filepath, encoding="utf-8") as f: fileContents = f.read() # Get all the text from file. # Set current text to file contents self.editor.delete(1.0, "end") self.editor.insert(1.0, fileContents) self.editor.edit_modified(False) self.file_path = filepath def file_save(self, event=None): if self.file_path == None: result = self.file_save_as() else: result = self.file_save_as(filepath=self.file_path) return result def file_save_as(self, event=None, filepath=None): if filepath == None: filepath = filedialog.asksaveasfilename( filetypes=(('Text files', '*.txt'), ('Python files', '*.py *.pyw'), ('All files', '*.*'))) #defaultextension='.txt' try: with open(filepath, 'wb') as f: text = self.editor.get(1.0, "end-1c") f.write(bytes(text, 'UTF-8')) self.editor.edit_modified(False) self.file_path = filepath self.set_title() return "saved" except FileNotFoundError: print('FileNotFoundError') return "cancelled" def file_run(self, event=None): import re f = open("/home/supriya/SIH/python/hello.py", "r") data = f.read() data = data.split('\n') print(data) for i in range(len(data) - 1): a = ".write" in data[i] if str(a) == str(True): del data[i] str1 = "\n".join(data) # print(str1) f = open("/home/supriya/SIH/python/hello.py", "w") f.write(str1) f.close() import json import pandas as pd import sys import hashlib import pyAesCrypt bufferSize = 64 * 1024 final_secret_key = "vishwas1234" f = pd.read_csv("/home/supriya/SIH/python/organization/datafile.csv") print(f) a = hashlib.sha224(final_secret_key.encode('utf-8')) final_secret_key = a.hexdigest() from netaddr import IPNetwork, IPAddress if IPAddress("192.168.0.224") in IPNetwork("192.168.0.0/24"): pyAesCrypt.decryptFile( '/home/supriya/SIH/python/organization/data.csv.aes', "../datafile2.csv", final_secret_key, bufferSize) ''' f = pd.read_csv("../datafile.csv") print(f)''' def file_quit(self, event=None): result = self.save_if_modified() if result != None: #None => Aborted or Save cancelled, False => Discarded, True = Saved or Not modified self.root.destroy() #sys.exit(0) def set_title(self, event=None): if self.file_path != None: title = os.path.basename(self.file_path) else: title = "Untitled" self.root.title(title + " - " + self.TITLE) def undo(self, event=None): self.editor.edit_undo() def redo(self, event=None): self.editor.edit_redo() def main(self, event=None): self.editor.bind("<Control-o>", self.file_open) self.editor.bind("<Control-O>", self.file_open) self.editor.bind("<Control-S>", self.file_save) self.editor.bind("<Control-s>", self.file_save) self.editor.bind("<Control-y>", self.redo) self.editor.bind("<Control-Y>", self.redo) self.editor.bind("<Control-Z>", self.undo) self.editor.bind("<Control-z>", self.undo)
class GUI(Frame): def __init__(self, master=None, val=0): super().__init__(master) self.master = master self.val = val self.parametros = [] self.actions = Enums.actions self.controller = Controller() self.initComp() def initComp(self): self.master.title("EDD - TytusDB") self.master.iconbitmap('team16/View/img/logo.ico') self.master.deiconify() self.centrar() if self.val == 1: self.main() elif self.val == 2: self.funciones() elif self.val == 3: self.reportes() def centrar(self): if self.val == 1: ancho = 500 alto = 500 elif self.val == 2: ancho = 1045 alto = 660 else: ancho = 1150 alto = 650 x_ventana = self.winfo_screenwidth() // 2 - ancho // 2 y_ventana = self.winfo_screenheight() // 2 - alto // 2 posicion = str(ancho) + "x" + str(alto) + "+" + str(x_ventana) + "+" + str(y_ventana - 35) self.master.resizable(width=False, height=False) self.master.geometry(posicion) def ventanaFunciones(self): v2 = Toplevel() self.master.iconify() image = Image.open('team16/View/img/function.png') background_image = ImageTk.PhotoImage(image.resize((1060, 680))) background_label = Label(v2, image=background_image) background_label.place(x=0, y=0, relwidth=1, relheight=1) v2.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(v2, self.master)) app2 = GUI(master=v2, val=2) app2.mainloop() def ventanaReporte(self): v3 = Toplevel() self.master.iconify() v3['bg'] = "#0f1319" v3.protocol("WM_DELETE_WINDOW", lambda: self.on_closing(v3, self.master)) app3 = GUI(master=v3, val=3) app3.mainloop() @staticmethod def on_closing(win, root): if messagebox.askokcancel("Salir", "¿Seguro que quieres salir?"): win.destroy() root.deiconify() def _on_mousewheel(self, event): try: self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") except: pass # region Menú principal def main(self): btnF = Button(text="FUNCIONES", bg="#33868a", bd=0, activebackground="#225b5e", font="Arial 18", pady=12, width=14, command=lambda: self.ventanaFunciones()) btnF.pack(side=TOP, pady=(150, 25)) btnR = Button(text="REPORTES", bg="#33868a", bd=0, activebackground="#225b5e", font="Arial 18", pady=12, width=14, command=lambda: self.ventanaReporte()) btnR.pack(side=TOP, pady=(0, 25)) btnS = Button(text="SALIR", bg="#bf4040", bd=0, activebackground="#924040", font="Arial 18", pady=0, width=14, command=lambda: exit()) btnS.pack(side=TOP, pady=(0, 25)) # endregion # region Ventana de funciones def funciones(self): lbl1 = Label(self.master, text="Bases de datos", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff") lbl1.grid(row=1, column=0, padx=(60, 85), pady=(100, 25)) lbl2 = Label(self.master, text="Tablas", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff") lbl2.grid(row=1, column=1, padx=(5, 0), columnspan=2, pady=(100, 25)) lbl3 = Label(self.master, text="Tuplas", font=("Century Gothic", 21), bg="#0f1319", fg="#ffffff") lbl3.grid(row=1, column=3, padx=(130, 150), pady=(100, 25)) # region Bases de datos btnCreateDB = Button(self.master, text=self.actions[1], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=16, command=lambda: self.simpleDialog(["database"], self.actions[1])) btnCreateDB.grid(row=2, column=0, sticky=W, padx=(70, 0), pady=(0, 25)) btnshowDBS = Button(self.master, text=self.actions[2], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=16, command=lambda: self.controller.execute(None, self.actions[2])) btnshowDBS.grid(row=3, column=0, sticky=W, padx=(70, 0), pady=(0, 25)) btnAlterDB = Button(self.master, text=self.actions[3], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=16, command=lambda: self.simpleDialog(["databaseOld", "databaseNew"], self.actions[3])) btnAlterDB.grid(row=4, column=0, sticky=W, padx=(70, 0), pady=(0, 25)) btnDropDB = Button(self.master, text=self.actions[4], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=16, command=lambda: self.simpleDialog(["database"], self.actions[4])) btnDropDB.grid(row=5, column=0, sticky=W, padx=(70, 0), pady=(0, 25)) btnFormat = Button(self.master, text=self.actions[23], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=16, command=lambda: self.controller.execute(None, self.actions[23])) btnFormat.grid(row=6, column=0, sticky=W, padx=(70, 0), pady=(0, 25)) # endregion # region Tablas btnCreateTb = Button(self.master, text=self.actions[5], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "tableName", "numberColumns"], self.actions[5])) btnCreateTb.grid(row=2, column=1, sticky=W, padx=(10, 0), pady=(0, 25)) btnDefinePK = Button(self.master, text=self.actions[9], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "table", "columns"], self.actions[9])) btnDefinePK.grid(row=3, column=1, sticky=W, padx=(10, 0), pady=(0, 25)) btnDropPK = Button(self.master, text=self.actions[10], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "table"], self.actions[10])) btnDropPK.grid(row=4, column=1, sticky=W, padx=(10, 0), pady=(0, 25)) btnShowTb = Button(self.master, text=self.actions[6], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database"], self.actions[6])) btnShowTb.grid(row=5, column=1, sticky=W, padx=(10, 0), pady=(0, 25)) btnAlterTb = Button(self.master, text=self.actions[13], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "tableOld", "tableNew"], self.actions[13])) btnAlterTb.grid(row=6, column=1, sticky=W, padx=(10, 0), pady=(0, 25)) btnDropTb = Button(self.master, text=self.actions[16], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "tableName"], self.actions[16])) btnDropTb.grid(row=2, column=2, sticky=W, padx=(5, 0), pady=(0, 25)) btnAlterAdd = Button(self.master, text=self.actions[14], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "tableName", "default"], self.actions[14])) btnAlterAdd.grid(row=3, column=2, sticky=W, padx=(5, 0), pady=(0, 25)) btnAlterDrop = Button(self.master, text=self.actions[15], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "tableName", "columnNumber"], self.actions[15])) btnAlterDrop.grid(row=4, column=2, sticky=W, padx=(5, 0), pady=(0, 25)) btnExtractTb = Button(self.master, text=self.actions[7], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "table"], self.actions[7])) btnExtractTb.grid(row=5, column=2, sticky=W, padx=(5, 0), pady=(0, 25)) btnExtractRangeTb = Button(self.master, text=self.actions[8], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=15, command=lambda: self.simpleDialog(["database", "table", "column", "lower", "upper"], self.actions[8])) btnExtractRangeTb.grid(row=6, column=2, sticky=W, padx=(5, 0), pady=(0, 25)) # endregion # region Tuplas: btnInsertTp = Button(self.master, text=self.actions[17], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["database", "table", "register"], self.actions[17])) btnInsertTp.grid(row=2, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) btnLoadfile = Button(self.master, text=self.actions[18], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["file", "database", "table"], self.actions[18])) btnLoadfile.grid(row=3, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) btnExtractTp = Button(self.master, text=self.actions[19], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["database", "table", "id"], self.actions[19])) btnExtractTp.grid(row=4, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) btnUpdateTp = Button(self.master, text=self.actions[20], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["database", "table", "register", "columns"], self.actions[20])) btnUpdateTp.grid(row=5, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) btnDeleteTp = Button(self.master, text=self.actions[21], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["database", "tableName", "columns"], self.actions[21])) btnDeleteTp.grid(row=6, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) btnTruncateTp = Button(self.master, text=self.actions[22], bg="#abb2b9", font=("Courier New", 14), borderwidth=0.5, pady=6, width=12, command=lambda: self.simpleDialog(["database", "tableName"], self.actions[22])) btnTruncateTp.grid(row=7, column=3, sticky=W, padx=(110, 0), pady=(0, 25)) # endregion # endregion # region Ventana de reporte def reportes(self): self.titulo3 = Label(self.master, text="Reporte bases de datos", bg="#0f1319", fg="#45c2c5", font=("Century Gothic", 42), pady=12) self.titulo3.pack(fill=X) self.scrollbarY = Scrollbar(self.master) self.scrollbarY.pack(side=RIGHT, fill=Y) self.scrollbarX = Scrollbar(self.master, orient='horizontal') self.scrollbarX.pack(side=BOTTOM, fill=X) self.listbox = Listbox(self.master, height=21, width=20, bg="#0f1319", bd=0, fg='#ffffff', font=("Century Gothic", 12)) self.listbox.place(x=65, y=122) self.listbox.bind("<<ListboxSelect>>", self.displayDBData) self.tableList = Combobox(self.master, state="readonly", width=30, font=("Century Gothic", 12)) self.tableList.place(x=360, y=120) self.tableList.set('Seleccione tabla...') self.tableList.bind("<<ComboboxSelected>>", self.displayTableData) self.tuplelist = Combobox(self.master, state="readonly", width=30, font=("Century Gothic", 12)) self.tuplelist.place(x=750, y=120) self.tuplelist.set('Seleccione tupla...') self.tuplelist.bind("<<ComboboxSelected>>", self.displayTupleData) self.canvas = Canvas(self.master, width=740, height=415, bg="#0f1319", highlightthickness=0) self.canvas.place(x=320, y=170) # self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set) self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) self.scrollbarY.config(command=self.canvas.yview) self.scrollbarX.config(command=self.canvas.xview) self.desplegarDB() # Mostrar lista de base de datos def desplegarDB(self): try: dblist = self.controller.execute(None, self.actions[2]) for db in dblist: self.listbox.insert(END, str(db)) png = self.controller.reportDB() bg_DB = ImageTk.PhotoImage(Image.open(png)) self.image_on_canvas = self.canvas.create_image(370, 207, anchor=CENTER, image=bg_DB) # self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set) # self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.master.mainloop() except: None # Mostrar lista de tablas def displayDBData(self, event): try: selection = event.widget.curselection() data = "" tmp = [] if selection: self.tableList.set('Seleccione tabla...') self.tuplelist.set('Seleccione tupla...') index = selection[0] data = event.widget.get(index) self.titulo3.configure(text=data) tmp.append(data) dbList = self.controller.execute(tmp, self.actions[6]) self.tableList["values"] = dbList png = self.controller.reportTBL(data) bg_TBL = ImageTk.PhotoImage(Image.open(png)) self.canvas.itemconfig(self.image_on_canvas, image=bg_TBL) self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set) self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.master.mainloop() except: None # Mostrar AVL de tabla def displayTableData(self, event): try: self.tuplelist.set('Seleccione tupla...') db = str(self.titulo3["text"]) tb = str(self.tableList.get()) tp = self.controller.getIndexes(db, tb) self.tuplelist["values"] = tp png = self.controller.reportAVL(db, tb) bg_AVL = ImageTk.PhotoImage(Image.open(png)) self.canvas.itemconfig(self.image_on_canvas, image=bg_AVL) self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set) self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.master.mainloop() except: None # Mostrar tupla def displayTupleData(self, event): try: db = str(self.titulo3["text"]) tb = str(self.tableList.get()) tp = str(self.tuplelist.get()) png = self.controller.reportTPL(db, tb, tp) # le envío el índice del árbol (tp) bg_TPL = ImageTk.PhotoImage(Image.open(png)) self.canvas.itemconfig(self.image_on_canvas, image=bg_TPL) self.canvas.config(xscrollcommand=self.scrollbarX.set, yscrollcommand=self.scrollbarY.set) self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.master.mainloop() except: None # endregion # region Digitador def simpleDialog(self, args, action): self.parametros.clear() tmp = [] dialog = Tk() dialog['bg'] = "#0f1319" dialog.title(action) dialog.resizable(False, False) dialog.update() dialog.deiconify() dim = len(args) for i in range(dim): Label(dialog, text=args[i] + ":", bg="#0f1319", fg="#ffffff", font=("Century Gothic", 12) ).grid(row=i, padx=(12, 1), pady=(2, 2), sticky=SW) if args[0] == "file": btnFile = Button(dialog, text="Examinar...", command=lambda: self.cargarArchivo(btnFile)) btnFile.grid(row=0, column=1, pady=(15, 2), padx=(0, 18), sticky="ew") for j in range(dim - 1): entry = Entry(dialog) entry.grid(row=j + 1, column=1, padx=(0, 18)) tmp.append(entry) else: for j in range(dim): entry = Entry(dialog) entry.grid(row=j, column=1, padx=(0, 18)) tmp.append(entry) tmp[0].focus_set() dialog.bind('<Return>', lambda event=None: self.ejecutar(dialog, tmp, action)) dialog.bind('<Escape>', lambda event=None: dialog.destroy()) submit = Button(dialog, text="OK", bg="#45c2c5", bd=0, pady=6, width=10, command=lambda: self.ejecutar(dialog, tmp, action)) submit.grid(row=dim + 1, columnspan=2, pady=(8, 10)) dialog.mainloop() # endregion def cargarArchivo(self, btn): filename = filedialog.askopenfilename(filetypes=[("csv files", "*.csv")]) if filename: self.parametros.append(filename) btn.configure(text=filename[filename.rfind('/') + 1:]) def ejecutar(self, dialog, args, action): for arg in args: if arg.get(): self.parametros.append(arg.get()) else: return messagebox.showerror("Oops", "Existen campos vacíos") response = self.controller.execute(self.parametros, action) if response in range(1, 8): self.parametros.clear() return messagebox.showerror("Error número: " + str(response), "Ocurrió un error en la operación.\nAsegúrese de introducir datos correctos") dialog.destroy()
bg="#cf6679", command=DeleteData) btn_delete.pack(side=RIGHT) #----------TABLES----------# scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL) scrollbary = Scrollbar(TableMargin, orient=VERTICAL) tree = ttk.Treeview(TableMargin, columns=("MemberID", "Firstname", "Lastname", "Gender", "Age", "Address", "Contact"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set) scrollbary.config(command=tree.yview) scrollbary.pack(side=RIGHT, fill=Y) scrollbarx.config(command=tree.xview) scrollbarx.pack(side=BOTTOM, fill=X) tree.heading('MemberID', text="MemberID", anchor=W) tree.heading("Firstname", text="Firstname", anchor=W) tree.heading("Lastname", text="Lastname", anchor=W) tree.heading("Gender", text="Gender", anchor=W) tree.heading("Age", text="Age", anchor=W) tree.heading("Address", text="Address", anchor=W) tree.heading("Contact", text="Contact", anchor=W) tree.column('#0', stretch=NO, minwidth=0, width=0) tree.column('#1', stretch=NO, minwidth=0, width=0) tree.column('#2', stretch=NO, minwidth=0, width=80) tree.column('#3', stretch=NO, minwidth=0, width=120) tree.column('#4', stretch=NO, minwidth=0, width=90) tree.column('#5', stretch=NO, minwidth=0, width=80)
class Gui(Frame): def log(self, value): self.text.configure(state="normal") self.text.insert(END, value + '\n') self.text.see(END) self.text.configure(state="disabled") def download(self): self.btn_download.configure(state="disabled") self.btn_download_txt.configure(state="disabled") username_text = self.entry_filename.get() if len(username_text) is 0 or len(username_text.split(','))!=3: messagebox.showinfo( title='Warning', message='Please input startpage and index with limit split by ,') else: usernames = username_text.split(',') self.core.root_path = self.root_path self.core.download_by_usernames(usernames, self.combobox_type.current()) self.btn_download.configure(state="normal") self.btn_download_txt.configure(state="normal") def download_txt(self): self.btn_download.configure(state="disabled") self.btn_download_txt.configure(state="disabled") filename = os.path.normpath(filedialog.askopenfilename( filetypes=(('text files', '*.txt'), ("all files", "*.*")))) if filename is not '.': print("done:"+filename) self.btn_download.configure(state="normal") self.btn_download_txt.configure(state="normal") def browse_directory(self): dir = os.path.normpath(filedialog.askdirectory()) if dir is not '': self.root_path = dir config.write_config('config.ini', 'Paths', 'root_path', self.root_path) self.entry_path.delete(0, END) self.entry_path.insert(0, self.root_path) self.core.root_path = self.root_path self.web.defaultDedirectory=self.root_path def createWidgets(self): frame_tool = Frame(self.window) frame_path = Frame(self.window) frame_log = Frame(self.window) self.lbl_username = Label( frame_tool, text='Start Page,EndPage,Limit,(split by ,):') self.entry_filename = Entry(frame_tool) self.btn_download = Button( frame_tool, text='Download', command=lambda: self.executor_ui.submit(self.download)) self.btn_download_txt = Button( frame_tool, text='Download txt', command=lambda: self.executor_ui.submit(self.download_txt)) self.lbl_type = Label(frame_path, text='Type:') self.combobox_type = ttk.Combobox(frame_path, state='readonly') self.combobox_type["values"] = ('all', 'image', 'torrent') self.combobox_type.current(0) self.lbl_path = Label(frame_path, text='Path:') self.entry_path = Entry(frame_path) self.entry_path.insert(END, self.root_path) self.btn_path_dialog = Button( frame_path, text="Browse", command=lambda: self.browse_directory()) self.scrollbar = Scrollbar(frame_log) self.text = Text(frame_log) self.text.configure(state="disabled") self.lbl_status = Label( self.window, text='-10086') frame_tool.pack(side=TOP, fill=X) self.lbl_username.pack(side=LEFT) self.entry_filename.pack(side=LEFT, fill=X, expand=True) self.btn_download.pack(side=LEFT) self.btn_download_txt.pack(side=LEFT) frame_path.pack(side=TOP, fill=X) self.lbl_type.pack(side=LEFT) self.combobox_type.pack(side=LEFT) self.lbl_path.pack(side=LEFT) self.entry_path.pack(side=LEFT, fill=X, expand=True) self.btn_path_dialog.pack(side=LEFT) self.text.pack(side=LEFT, fill=BOTH, expand=True) self.scrollbar.pack(side=LEFT, fill=Y) frame_log.pack(side=TOP, fill=BOTH, expand=True) self.scrollbar.config(command=self.text.yview) self.text.config(yscrollcommand=self.scrollbar.set) self.text.focus() self.lbl_status.pack(side=LEFT, fill=X, expand=True) def __init__(self, version): self.core = Core(self.log) self.web = Web(self.log) master = Tk() Frame.__init__(self, master) master.title('AV Downloader ' + version) root_path_config = config.read_config( 'config.ini', 'Paths', 'root_path') self.root_path = os.path.join( os.path.expanduser("~"), "downloads") if root_path_config is '' else root_path_config self.executor_ui = futures.ThreadPoolExecutor(1) self.window = master self.pack() self.createWidgets()
class Application(object): def __init__(self): self.__createGUI() self.treeIndex = 1 self.totals = 0 self.totalData = [["用户ID", "OLT名称", "PON端口", "用户状态", "时间"]] self.excelData = [] def __createGUI(self): self.root = mtk.Tk() self.root.title("宽带通查询助手1.0") self.root.geometry("860x500") self.loadExcel = mtk.LabelFrame(text="导入Excel文件", fg="blue") self.loadExcel.place(x=50, y=20, width=220, height=100) self.fileChoose = mtk.Button( self.loadExcel, text="选择文件", command=lambda: self.thread_it(self.__loadExcel)) self.fileChoose.place(x=70, y=5, width=80, height=30) self.outExcel = mtk.Button( self.loadExcel, text="导出Excel", command=lambda: self.thread_it(self._saveExcel)) self.outExcel.place(x=70, y=43, width=80, height=30) self.btnBox = mtk.LabelFrame(text="任务栏", fg="blue") self.btnBox.place(x=320, y=20, width=220, height=100) self.btnStart = mtk.Button(self.btnBox, text="开始", command=lambda: self.thread_it(self.start)) self.btnStart.place(x=70, y=5, width=80, height=30) self.btnEnd = mtk.Button(self.btnBox, text="退出", command=lambda: self.thread_it(self.stop)) self.btnEnd.place(x=70, y=43, width=80, height=30) self.staticData = mtk.LabelFrame(self.root, text="数量统计", fg="blue") self.staticData.place(x=583, y=20, width=220, height=100) self.labelDataTotal = mtk.Label(self.staticData, text="总导入数量:") self.labelDataTotal.place(x=20, y=5, width=80, height=30) self.entryDataTotal = mtk.Label(self.staticData, text="0") self.entryDataTotal.place(x=120, y=5, width=80, height=30) self.labelDoneTotal = mtk.Label(self.staticData, text="已完成数量:") self.labelDoneTotal.place(x=20, y=40, width=80, height=30) self.entryDoneTotal = mtk.Label(self.staticData, text="0") self.entryDoneTotal.place(x=120, y=40, width=80, height=30) self.showDataBox = mtk.LabelFrame(text="数据展示区域", fg="blue") self.showDataBox.place(x=50, y=150, width=760, height=300) title = ['1', '2', '3', '4', '5', '6'] self.box = ttk.Treeview(self.showDataBox, columns=title, show='headings') self.box.place(x=20, y=15, width=730, height=250) self.box.column('1', width=80, anchor='center') self.box.column('2', width=120, anchor='center') self.box.column('3', width=180, anchor='center') self.box.column('4', width=80, anchor='center') self.box.column('5', width=100, anchor='center') self.box.column('6', width=150, anchor='center') self.box.heading('1', text='序号') self.box.heading('2', text='用户ID') self.box.heading('3', text='OLT名称') self.box.heading('4', text='PON端口') self.box.heading('5', text='用户状态') self.box.heading('6', text='时间') self.VScroll1 = Scrollbar(self.box, orient='vertical', command=self.box.yview) self.VScroll1.pack(side="right", fill="y") self.box.configure(yscrollcommand=self.VScroll1.set) def deleteTree(self): x = self.box.get_children() for item in x: self.box.delete(item) def __loadExcel(self): excelPath = filedialog.askopenfilename(title=u'选择文件') if excelPath: try: self.totalData = [["用户ID", "OLT名称", "PON端口", "用户状态", "时间"]] self.treeIndex = 1 self.excelData = [] self.deleteTree() wb = load_workbook(excelPath) ws = wb.active self.excelData = [i[0] for i in list(ws.values)[1:]] self.totals = ws.max_row - 1 showinfo("提示信息", "共导入{}条数据".format(self.totals)) self.entryDataTotal.configure(text=f"{self.totals}") except: showerror("错误信息", "请选择正确格式的Excel文件!") else: showerror("错误信息", "请导入文件!") async def __getContent(self, semaphore, userID): link = f"http://220.113.1.44/wap/ShowPic.aspx?userid={userID}" headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Host': '220.113.1.44', 'Pragma': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36' } async with semaphore: async with aiohttp.ClientSession(headers=headers) as session: async with await session.get(link) as resp: content = await resp.text() await asyncio.sleep(random.uniform(0, 2)) return content async def __crawler(self, semaphore, userID): content = await self.__getContent(semaphore, userID) print(content) print(userID) print('-' * 100) olt = re.findall(r"OLT名称:(.*?)<", content) pon = re.findall(r"PON端口:(.*?)<", content) status = re.findall(r"用户状态:(.*?)<", content) date = re.findall(r"时间:(.*?)<", content) treeData = [ self.treeIndex, userID, olt[0].replace(" ", "") if olt else None, pon[0].replace(" ", "") if pon else None, status[0].replace(" ", "") if status else None, date[0].replace(" ", "") if date else None, ] self.totalData.append(treeData[1:]) self.box.insert("", "end", values=treeData) self.entryDoneTotal.configure(text=self.treeIndex) self.treeIndex += 1 self.box.yview_moveto(1.0) def _saveExcel(self): if not self.totalData: showerror("错误信息", "当前不存在任何数据!") return excelPath = filedialog.asksaveasfilename( title=u'保存文件', filetypes=[("xlsx", ".xlsx")]) + ".xlsx" if excelPath.strip(".xlsx"): wb = Workbook() ws = wb.active for line in self.totalData: ws.append(line) wb.save(excelPath) showinfo("提示信息", "保存成功!") async def taskManager(self, dataList, func): tasks = [] sem = asyncio.Semaphore(5) for userId in dataList: task = asyncio.ensure_future(func(sem, userId)) tasks.append(task) await asyncio.gather(*tasks) def start(self): if self.totals > 0: new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) loop = asyncio.get_event_loop() loop.run_until_complete( self.taskManager(self.excelData, self.__crawler)) showinfo("提示信息", "任务结束!") else: showerror("错误信息", "当前无可查数据!") def stop(self): os._exit(0) @staticmethod def thread_it(func, *args): t = threading.Thread(target=func, args=args) t.setDaemon(True) t.start() def run(self): self.root.mainloop()
def __init__(self): """ Constructor for the GUI. """ # Establish tkinter object self.root = Tk() self.root.title("ProPlanG") self.process_data = [] self.prev_visited = [] # data of the process that is currently being moved # x and y are the coordinates, item is the tag of the object group self.drag_x = 0 self.drag_y = 0 self.drag_item = None # Create Tkinter Menu (menubar on top, below window title) menubar = Menu(self.root) # Create pulldown menu (set tearoff=0 to disable detaching the menu) filemenu = Menu(menubar, tearoff=0) debugmenu = Menu(menubar, tearoff=0) # Menu content menubar.add_cascade(label="File", menu=filemenu) menubar.add_cascade(label="Settings", menu=debugmenu) # Filemenu content filemenu.add_command(label="Open...", command=self.read_config_file) # Debugmenu content self.detailed_arrow = BooleanVar(self.root, False) debugmenu.add_checkbutton(label="Show detailed arrows", variable=self.detailed_arrow, command=self.handle_arrow_drawing) self.arrow_split = BooleanVar(self.root, False) debugmenu.add_checkbutton(label="Directly connect arrows", variable=self.arrow_split, command=self.handle_arrow_drawing) # scrollbar x_scrollbar = Scrollbar(self.root, orient="horizontal") y_scrollbar = Scrollbar(self.root, orient="vertical") # sizegrip sizegrip = Sizegrip(self.root) # display the menu self.root.config(menu=menubar) # Prepare the main canvas self.main_canvas = Canvas(self.root, width=1000, height=500, borderwidth=1, scrollregion=(0, 0, 2000, 1000), xscrollcommand=x_scrollbar.set, yscrollcommand=y_scrollbar.set) # enable actual scrolling x_scrollbar.config(command=self.main_canvas.xview) y_scrollbar.config(command=self.main_canvas.yview) # bind mouse buttons to the drag functions self.main_canvas.bind("<ButtonPress-1>", self.drag_start) self.main_canvas.bind("<ButtonRelease-1>", self.drag_stop) self.main_canvas.bind("<B1-Motion>", self.drag) # place widgets in grid x_scrollbar.pack(fill="x", side="bottom", expand=False) y_scrollbar.pack(fill="y", side="right", expand=False) sizegrip.pack(in_=x_scrollbar, side="bottom", anchor="se") self.main_canvas.pack(fill="both", side="left", expand=True) # start the gui self.root.mainloop()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="#8080FF") self.parent = parent self.initUI() def initUI(self): self.parent.title("EQ GuildViewer 0.1") fontb = Font(size=12, weight="bold") # inicializo variables self.ant = None self.lastLine = 0 self.name = "" # frame padre area = Frame(self) area.pack(side=BOTTOM, fill=BOTH, expand=1) areab = Frame(self) areab.pack(side=TOP, fill=BOTH, expand=1) # scroll players self.scrollbar2 = Scrollbar(areab, orient=VERTICAL) # construimos un menu con todos los nombres del diccionario y un boton self.refreshButton = Button(areab, text="""PARSEA!""", command=self.onRefresh, bd=2, relief="groove") self.listboxLogs = Listbox( areab, width=50, activestyle="none", highlightthickness=0, yscrollcommand=self.scrollbar2.set, relief=RIDGE ) self.listboxLogs.pack(side=LEFT, fill=Y) self.scrollbar2.pack(side=LEFT, fill=Y) self.refreshButton.pack(side=LEFT, fill=BOTH, expand=1) for player in optionsDictionary: self.listboxLogs.insert(END, player) # scroll self.scrollbar = Scrollbar(area, orient=VERTICAL) self.scrollbar.pack(side=RIGHT, fill=Y) # area1 area1 = Frame(area) area1.pack(side=LEFT, fill=Y) lbl = Label(area1, text="Name") self.listbox = Listbox( area1, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl.pack(side=TOP) self.listbox.pack(side=BOTTOM, fill=Y, expand=1) # area2 area2 = Frame(area) area2.pack(side=LEFT, fill=Y) lbl2 = Label(area2, text="Level") self.listbox2 = Listbox( area2, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl2.pack(side=TOP) self.listbox2.pack(side=BOTTOM, fill=Y, expand=1) # area3 area3 = Frame(area) area3.pack(side=LEFT, fill=Y) lbl3 = Label(area3, text="Class") self.listbox3 = Listbox( area3, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl3.pack(side=TOP) self.listbox3.pack(side=BOTTOM, fill=Y, expand=1) # area4 area4 = Frame(area) area4.pack(side=LEFT, fill=Y) lbl4 = Label(area4, text="Race") self.listbox4 = Listbox( area4, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl4.pack(side=TOP) self.listbox4.pack(side=BOTTOM, fill=Y, expand=1) # area3 area5 = Frame(area) area5.pack(side=LEFT, fill=Y) lbl5 = Label(area5, text="Zone") self.listbox5 = Listbox( area5, yscrollcommand=self.scrollbar.set, font=fontb, relief=FLAT, highlightthickness=0, activestyle="none" ) lbl5.pack(side=TOP) self.listbox5.pack(side=BOTTOM, fill=Y, expand=1) self.pack(fill=BOTH, expand=1) # config-scrollbar self.scrollbar.config(command=self.yview) self.scrollbar2["command"] = self.listboxLogs.yview # bindeos de acciones self.listbox.bind("<<ListboxSelect>>", self.onSelect) self.listbox.bind("<MouseWheel>", self.onTest) self.listbox2.bind("<<ListboxSelect>>", self.onSelect) self.listbox2.bind("<MouseWheel>", self.onTest) self.listbox3.bind("<<ListboxSelect>>", self.onSelect) self.listbox3.bind("<MouseWheel>", self.onTest) self.listbox4.bind("<<ListboxSelect>>", self.onSelect) self.listbox4.bind("<MouseWheel>", self.onTest) self.listbox5.bind("<<ListboxSelect>>", self.onSelect) self.listbox5.bind("<MouseWheel>", self.onTest) self.listboxLogs.bind("<<ListboxSelect>>", self.onSelectPlayer) # mostrar la barra de scroll def yview(self, *args): self.listbox.yview(*args) self.listbox2.yview(*args) self.listbox3.yview(*args) self.listbox4.yview(*args) self.listbox5.yview(*args) # accion de la rueda del raton def onTest(self, val): return "break" # seleccionar un elementos de una listbox def onSelect(self, val): try: if self.ant != None: self.listbox.itemconfig(self.ant, background="#FFFFFF") self.listbox2.itemconfig(self.ant, background="#FFFFFF") self.listbox3.itemconfig(self.ant, background="#FFFFFF") self.listbox4.itemconfig(self.ant, background="#FFFFFF") self.listbox5.itemconfig(self.ant, background="#FFFFFF") self.listbox.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox2.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox3.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox4.itemconfig(val.widget.curselection(), background="#C0C0C0") self.listbox5.itemconfig(val.widget.curselection(), background="#C0C0C0") self.ant = val.widget.curselection() except: None # print('No hay valores') # dependiendo de que nombre se elija en el menu cargamos en lastLine la linea de ese nombre del diccionario def onSelectPlayer(self, val): try: self.name = val.widget.get(val.widget.curselection()) self.lastLine = optionsDictionary[self.name] # print(self.name, ' ', self.lastLine) except: None # print('No hay valores') # recorremos el fichero log al clickar sobre el boton 'Refresh!' def onRefresh(self): if self.name != "": yes = False count = 0 dictionary = {} dictionaryAuxiliar = {} stringLog = "../eqlog_" + str(self.name) + "_project1999.txt" with open(stringLog, "r") as log: for i in range(int(self.lastLine)): next(log) count = count + 1 for line in log: match = re.match("\[.*\] \[(.*) (.*)\] (.*) \((.*)\) <.*> ZONE: (.*)", line) matchRole = re.match("\[.*\] \[(.*)\] (.*) <.*>", line) matchToken = re.match("\[.*\] You say, 't0000'", line) matchTokenI = re.match("\[.*\] You say, 't0001'", line) if matchTokenI != None: yes = True elif match != None and yes: dictionaryAuxiliar[match.group(3)] = ( match.group(1), match.group(2), match.group(4), match.group(5), ) elif matchRole != None and yes: dictionaryAuxiliar[matchRole.group(2)] = [(matchRole.group(1))] elif matchToken != None and yes: dictionary = dictionaryAuxiliar.copy() dictionaryAuxiliar.clear() yes = False count = count + 1 # bucle para sacar datos, primero eliminamos todo lo que haya self.listbox.delete(0, self.listbox.size()) self.listbox2.delete(0, self.listbox2.size()) self.listbox3.delete(0, self.listbox3.size()) self.listbox4.delete(0, self.listbox4.size()) self.listbox5.delete(0, self.listbox5.size()) for member in dictionary: self.listbox.insert(END, member) self.listbox2.insert(END, dictionary[member][0]) try: self.listbox3.insert(END, dictionary[member][1]) self.listbox4.insert(END, dictionary[member][2]) self.listbox5.insert(END, dictionary[member][3]) except IndexError as error: self.listbox3.insert(END, "-") self.listbox5.insert(END, "-") self.listbox4.insert(END, "-") # print(dictionary) # print('Longitud', len(dictionary)) # guardamos la linea ultima leida en el diccionario # self.lastLine = count # optionsDictionary[self.name] = count # print('Despues:', optionsDictionary) # guardamos el diccionario en el archivo options options = open("options.txt", "w") for player in optionsDictionary: options.write(str(player) + ":" + str(optionsDictionary[player])) options.close()
class CodeEdit: def __init__(self, window): window.title('Untitled - CodeEdit') window.geometry('960x540') font_specs = ('Calibri', 11) self.window = window self.filename = None self.textarea = Text(window, font=font_specs) self.scroll = Scrollbar(window, command=self.textarea.yview) self.textarea.configure(yscrollcommand=self.scroll.set) self.textarea.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True) self.scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y) self.menubar = Menubar(self) self.statusbar = Statusbar(self) def set_window_title(self, name=None): if name: self.window.title(f'{name} - CodeEdit') else: self.window.title('Untitled - CodeEdit') def new_file(self): self.textarea.delete(1.0, tkinter.END) self.filename = None self.set_window_title() def open_file(self): self.filename = filedialog.askopenfilename( defaultextension='.txt', filetypes=[('All Files', '*.*'), ('Text Files', '*.txt'), ('Python Scripts', '*.py'), ('Markdown Documents', '*.md'), ('JavaScript Files', '*.js'), ('HTML Documents', '*.html'), ('CSS Documents', '*.css')]) if self.filename: self.textarea.delete(1.0, tkinter.END) with open(self.filename, 'r') as f: self.textarea.insert(1.0, f.read()) self.set_window_title(self.filename) def save(self): if self.filename: try: textarea_content = self.textarea.get(1.0, tkinter.END) with open(self.filename, 'w') as f: f.write(textarea_content) except Exception as e: print(e) else: self.save_as() def save_as(self): try: new_file = filedialog.asksaveasfilename( initialfile="Untitled.txt", defaultextension=".txt", filetypes=[("All Files", "*.*"), ("Text Files", "*.txt"), ("Python Scripts", "*.py"), ("Markdown Documents", "*.md"), ("JavaScript Files", "*.js"), ("HTML Documents", "*.html"), ("CSS Documents", "*.css")]) textarea_content = self.textarea.get(1.0, tkinter.END) with open(new_file, "w") as f: f.write(textarea_content) self.filename = new_file self.set_window_title(self.filename) except Exception as e: print(e)
class ClipBoardBox(ttk.Labelframe): def __init__( self, controller, *args, ): ttk.Labelframe.__init__(self, *args, text="Clipboard") self.clipboard = controller.clipboard self.thumbnails = [] self.tiles = [] self.canvas_height = 300 self.trash_image = load_tk_image_from_bytes_array(trash_bytes) self.nextid = 0 self.canvas = Canvas(self, relief="sunken") self.canvas.config(width=200, height=self.canvas_height, highlightthickness=0) self.scrollbar = Scrollbar(self) self.scrollbar.config(command=self.on_scroll_bar) self.canvas.config(yscrollcommand=self.scrollbar.set) self.scrollbar.pack(side="right", fill="y") self.canvas.pack(side="right", expand=True, fill="both") self.canvas_frame = Frame(self.canvas, border=0, highlightthickness=0) self.canvas_frame.bind("<MouseWheel>", self._on_mouse_wheel) self.canvas.create_window(0, 0, window=self.canvas_frame, anchor='nw') self.canvas.bind("<MouseWheel>", self._on_mouse_wheel) self.canvas_frame.config(width=200, height=self.winfo_height()) self.canvas.config(scrollregion=(0, 0, 200, self.canvas_height)) self.canvas.bind("<Enter>", self.mouse_enter) self.canvas.bind("<Leave>", self.mouse_leave) self.canvas.bind("<Motion>", self.on_mouse_move) self.canvas.bind("<Button-1>", self.on_click) self.canvas.after_idle(self.refresh) self.bind("<MouseWheel>", self._on_mouse_wheel) self.grip = ttk.Sizegrip(self) self.grip.place(relx=1.0, rely=1.0, anchor="se") self.grip.bind("<ButtonPress-1>", self.on_press) self.grip.bind("<B1-Motion>", self.on_resize) self.grip.bind("<ButtonRelease-1>", self.on_release) # def on_resize(self, event): # x_change = event.x_root - self.winfo_rootx() # x_change = 1 if x_change < 1 else x_change # y_change = event.y_root - self.winfo_rooty() # y_change = 1 if y_change < 1 else y_change # # self.minsize(self.winfo_reqwidth(), self.winfo_reqheight()) # self.geometry("%sx%s" % (x_change, y_change)) def on_press(self, event): self.grip["cursor"] = "bottom_right_corner" def on_resize(self, event): x_change = event.x_root - self.winfo_rootx() x_change = 1 if x_change < 1 else x_change y_change = event.y_root - self.winfo_rooty() y_change = 1 if y_change < 1 else y_change # self.minsize(self.winfo_reqwidth(), self.winfo_reqheight()) self.geometry("%sx%s" % (x_change, y_change)) def on_release(self, event): self.grip["cursor"] = "arrow" self.refresh() def mouse_enter(self, event): pass def mouse_leave(self, event): pass def on_click(self, event): y = int(event.y + (float(self.canvas.yview()[0]) * self.canvas_height)) x = event.x for t in self.tiles: if t.is_in_row(y): mode = t.on_click(x, y) if not mode: self.clipboard.selected_layer = t.layer t.layer.activate() self.refresh() else: t.deactivate() def on_mouse_move(self, event): y = int(event.y + (float(self.canvas.yview()[0]) * self.canvas_height)) x = event.x for t in self.tiles: if t.active: if t.is_in_row(y): continue else: t.deactivate() elif t.is_in_row(y): t.activate() def refresh(self, event=None): self.winfo_toplevel().update_idletasks() self.canvas.delete("all") self.thumbnails = [] self.tiles = [] if self.clipboard.layers: i = 0 y_offset = 10 y_padding = 10 tile_height = 80 x = 10 width = 80 height = tile_height child_offset = 0.5 * tile_height for c in self.clipboard.layers: y = i * tile_height + y_offset + i * y_padding t = ClipTile(self, c) self.tiles.append(t) t.set_dimensions(x, y, width, height) self.place_tile(t) if c is self.clipboard.selected_layer: self.select_tile(t) i += 1 height = i * tile_height + y_offset + i * y_padding frameheight = self.canvas_frame.winfo_height() height = height if height > frameheight else frameheight self.canvas_height = height self.canvas_frame.config(width=200, height=self.canvas_height) self.canvas.config(scrollregion=(0, 0, 200, self.canvas_height)) else: pass def place_tile(self, tile): tn = ImageTk.PhotoImage(tile.get_thumbnail(tile.height)) self.thumbnails.append(tn) tile.references.append( self.canvas.create_image(tile.x + 0.5 * tile.width, tile.y + 0.5 * tile.height, image=tn)) tile.references.append( self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=1)) tile.references.append( self.canvas.create_text(tile.x + tile.width + 10, tile.y, font="CourierNew 8", text=tile.id, anchor="nw")) tile.references.append( self.canvas.create_text( tile.x + tile.width + 10, tile.y + 10, font="CourierNew 8", text=f"Size: {tile.layer.width}px x {tile.layer.height}px", anchor="nw")) def activate_tile(self, tile): tile.active_references.extend([ self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=2), self.canvas.create_image(tile.trash_x, tile.trash_y, anchor="nw", image=self.trash_image), ]) def deactivate_tile(self, tile): self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=1) for r in tile.active_references: self.canvas.delete(r) def select_tile(self, tile): tile.references.append( self.canvas.create_rectangle(tile.x, tile.y, tile.x + tile.width, tile.y + tile.height, outline="#000000", width=3)) def _on_mouse_wheel(self, event): if platform.system() == 'Windows': self.canvas.yview_scroll(-1 * int(event.delta / 120), 'units') elif platform.system() == 'Darwin': self.canvas.yview_scroll(-1 * int(event.delta), 'units') else: if event.num == 4: self.canvas.yview_scroll(-1, 'units') elif event.num == 5: self.canvas.yview_scroll(1, 'units') def on_scroll_bar(self, move_type, move_units, __=None): if move_type == "moveto": self.canvas.yview("moveto", move_units) def delete_layer(self, layer): self.clipboard.del_layer(layer) self.clipboard.selected_layer = self.clipboard.layers[ 0] if self.clipboard.layers else None self.canvas.after_idle(self.refresh)
relheight=0.25, ) middle_button_filepath['text'] = '< ---' # BOTTOM BLOCK background_bot = ttk.Frame(window) background_bot.place(anchor='n', relx=0.5, rely=0.45, relwidth=0.9, relheight=0.5) bot_text_text = Text(background_bot, bg="#FCFCFC", fg='black', wrap="word", font='Consolas 10', state='disabled') bot_text_text.place(anchor='center', relx=0.5, rely=0.5, relwidth=1, relheight=1) bot_scroll_text = Scrollbar(bot_text_text, command=bot_text_text.yview) bot_scroll_text.pack(side='right', fill='y') bot_text_text.config(yscrollcommand=bot_scroll_text.set) window.mainloop()
class RssPage(tk.Frame): # 继承Frame类 def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.rss_list = [] self.rss_path = './conf/rss_config.pickle' if not os.path.isfile(self.rss_path): self.create_config() self.var_rss_link = StringVar() self.var_rss_site = StringVar() self.var_rss_name = StringVar() self.label_link = Label(self, text='链接:', anchor=W) self.label_name = Label(self, text='别名:', anchor=W) self.label_site = Label(self, text='站点:', anchor=W) self.entry_rss_link = tk.Entry(self, textvariable=self.var_rss_link, width=58, borderwidth=3, font=('Helvetica', '12')) self.entry_rss_name = tk.Entry(self, textvariable=self.var_rss_name, width=58, borderwidth=3, font=('Helvetica', '12')) self.entry_rss_site = tk.Entry(self, textvariable=self.var_rss_site, width=58, borderwidth=3, font=('Helvetica', '12')) self.button_add = tk.Button(self, text='添加', width=6, command=self.add_to_list) self.frame_m = Frame(self) self.scrollBar = Scrollbar(self.frame_m) self.tree = Treeview(self.frame_m, columns=('c1', 'c2', 'c3'), show="headings", yscrollcommand=self.scrollBar.set) self.button_delete = tk.Button(self, text='删除', command=self.delete_rss) self.button_save = tk.Button(self, text='保存', command=self.save_config) self.create_page() self.load_config() def load_config(self): try: with open(self.rss_path, "rb") as rss_file: rss_list = pickle.load(rss_file) for item in rss_list: self.tree.insert('', 'end', values=[item[0], item[1], item[2]]) except FileNotFoundError: pass def create_config(self): with open(self.rss_path, 'wb') as rss_file: self.rss_list = [] pickle.dump(self.rss_list, rss_file) def save_config(self): rss_all = self.tree.get_children() self.rss_list.clear() for item in rss_all: value_rss_link = self.tree.item(item, 'values')[0] value_rss_name = self.tree.item(item, 'values')[1] value_rss_site = self.tree.item(item, 'values')[2] rss_tuple = (value_rss_link, value_rss_name, value_rss_site) self.rss_list.append(rss_tuple) with open(self.rss_path, 'wb') as rss_file: pickle.dump(self.rss_list, rss_file) def create_page(self): self.label_link.place(x=30, y=30, width=80, height=30) self.label_name.place(x=30, y=70, width=80, height=30) self.label_site.place(x=330, y=70, width=80, height=30) self.entry_rss_link.place(x=80, y=30, width=640, height=30) self.entry_rss_name.place(x=80, y=70, width=200, height=30) self.entry_rss_site.place(x=380, y=70, width=200, height=30) self.button_add.place(x=640, y=70, width=80, height=30) self.frame_m.place(x=55, y=120, width=680, height=420) # 在Frame容器中创建滚动条 self.scrollBar.pack(side=RIGHT, fill=Y) # 在Frame容器中使用Treeview组件实现表格功能 # Treeview组件,三列,显示表头,带垂直滚动条 # 设置每列宽度和对齐方式 self.tree.column('c1', width=400, anchor='center') self.tree.column('c2', width=140, anchor='center') self.tree.column('c3', width=120, anchor='center') # 设置每列表头标题文本 self.tree.heading( 'c1', text='链接', command=lambda: self.treeview_sort_column(self.tree, 'c1', False)) self.tree.heading( 'c2', text='别名', command=lambda: self.treeview_sort_column(self.tree, 'c2', False)) self.tree.heading( 'c3', text='站点名称', command=lambda: self.treeview_sort_column(self.tree, 'c3', False)) # 左对齐,纵向填充 self.tree.pack(side=LEFT, fill=Y) # self.tree.bind('<Double-1>', self.treeviewclick) # Treeview组件与垂直滚动条结合 self.scrollBar.config(command=self.tree.yview) # 删除按钮 self.button_delete.place(x=160, y=550, width=120, height=30) # 刷新按钮 self.button_save.place(x=460, y=550, width=120, height=30) def treeview_sort_column(self, tv, col, reverse): # Treeview、列名、排列方式 ll = [(tv.set(k, col), k) for k in tv.get_children('')] ll.sort(reverse=reverse) # 排序方式 for index, (val, k) in enumerate(ll): # 根据排序后索引移动 tv.move(k, '', index) tv.heading(col, command=lambda: self.treeview_sort_column( tv, col, not reverse)) # 重写标题,使之成为再点倒序的标题 def add_to_list(self): value_rss_site = self.var_rss_site.get() value_rss_name = self.var_rss_name.get() value_rss_link = self.var_rss_link.get() values = [value_rss_link, value_rss_name, value_rss_site] self.tree.insert('', 'end', values=values) self.var_rss_link.set('') self.var_rss_name.set('') self.var_rss_site.set('') def delete_rss(self): if not self.tree.selection(): tk.messagebox.showerror('抱歉', '你还没有选择,不能删除') return for item in self.tree.selection(): self.tree.delete(item)
def view_program_history(_=0): try: history_list = session.query(ProgramHistory).all() except: messagebox.showerror("Error", "Couldn't Fetch The Program History From The DB") session.rollback() return subwindow = Toplevel(window) subwindow.title("Program History") subwindow.geometry("1920x1080") canvas = Canvas(subwindow) scrollable_frame = Frame(canvas) scrollable_frame.bind( "<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")) ) canvas.create_window((0, 0), window=scrollable_frame, anchor="nw") scrollbary = Scrollbar(subwindow, orient="vertical", command=canvas.yview) scrollbarx = Scrollbar(subwindow, orient="horizontal", command=canvas.xview) canvas.configure(xscrollcommand=scrollbarx.set) canvas.configure(yscrollcommand=scrollbary.set) scrollbary.pack(side="right", fill="y") scrollbarx.pack(side="bottom", fill="x") canvas.pack(side="left", fill="both", expand=True) ttk.Label(scrollable_frame, text="index").grid(row=0, column=0, ipadx=1, ipady=1) ttk.Label(scrollable_frame, text="User Name").grid( row=0, column=1, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program ID").grid( row=0, column=2, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program Name").grid( row=0, column=3, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Program State").grid( row=0, column=4, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="Start Time").grid( row=0, column=5, ipadx=1, ipady=1 ) ttk.Label(scrollable_frame, text="End Time").grid(row=0, column=6, ipadx=1, ipady=1) for i in range(len(history_list)): programname = "-UNKNOWN-" try: program = session.query(Program).filter_by(gid=history_list[i].gid).first() programname = program.pname except: session.rollback() ttk.Label(scrollable_frame, text=i + 1).grid( row=i + 1, column=0, ipadx=1, ipady=1 ) ttk.Label( scrollable_frame, text=history_list[i].username, ).grid(row=i + 1, column=1, ipadx=1, ipady=1) ttk.Label( scrollable_frame, text=history_list[i].pid, ).grid(row=i + 1, column=2, ipadx=1, ipady=1) ttk.Label( scrollable_frame, text=programname, ).grid(row=i + 1, column=3, ipadx=1, ipady=1) ttk.Label( scrollable_frame, text=history_list[i].pstate, ).grid(row=i + 1, column=4, ipadx=1, ipady=1) ttk.Label( scrollable_frame, text=history_list[i].pstart, ).grid(row=i + 1, column=5, ipadx=1, ipady=1) ttk.Label( scrollable_frame, text=history_list[i].pend, ).grid(row=i + 1, column=6, ipadx=1, ipady=1)
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 TextEditor(Frame): def __init__(self, master=None) -> None: super().__init__(master) self.master = master self.line_numbers = TextLineNumbers(self, width=20) self.syntax = Syntax(master) self.add_scrollbar() bar = Toolbar(master, self.text) bar.open_file_button() bar.save_file_button() bar.save_file_as_button() bar.post_to_hastebin_button() bar.run_button() bar.close_editor_button() bar.undo_button() bar.redo_button() bar.cut_button() bar.copy_button() bar.paste_button() bar.find_and_replace_button() bar.select_all_button() bar.deselect_all_button() bar.keyword_highlighting_button() bar.builtin_highlighting_button() bar.number_highlighting_button() bar.comment_highlighting_button() bar.string_highlighting_button() bar.definition_highlighting_button() bar.stackoverflow_button() def add_scrollbar(self) -> None: self.y_scrollbar = Scrollbar(self.master) self.x_scrollbar = Scrollbar(self.master, orient="horizontal") self.y_scrollbar.pack(side=RIGHT, fill=Y) self.x_scrollbar.pack(side=BOTTOM, fill=X) self.line_numbers.pack(side="left", fill=Y) self.text = CustomText( self.master, yscrollcommand=self.y_scrollbar.set, xscrollcommand=self.x_scrollbar.set, highlightcolor="white", tabs=28, wrap=NONE, undo=True, maxundo=1, ) self.text.pack(fill=BOTH, side=RIGHT, expand=True) self.text.bind("<<Change>>", self.on_change) self.text.bind("<Configure>", self.on_change) self.text.bind("<KeyRelease>", self.on_key_release) self.y_scrollbar.config(command=self.text.yview) self.x_scrollbar.config(command=self.text.xview) self.line_numbers.attach(self.text) def on_change(self, event) -> None: self.line_numbers.redraw() def on_key_release(self, event) -> None: self.syntax.highlight(self.text)