class Notepad(tk.Tk): """A notepad application""" def __init__(self): super().__init__() self.withdraw() #this is how to check platform & set zoom status platform = self.tk.call('tk', 'windowingsystem') self.wm_state('zoomed') if platform == 'win32' else self.attributes( '-zoomed', 1) # code for naming file and about file variables. self.file = pathlib.Path.cwd() / 'Untitled_notepad.txt' self.file_defaults = { 'defaultextension': '*', 'filetypes': [('All Files', '.*')]} # code to find,search and replace variables self.query = None self.matches = None self.findnext = None self.findreplace = None # code to do main menu setup self.menu = tk.Menu(self) self.configure(menu=self.menu) self.menu_file = tk.Menu(self.menu, tearoff=False) self.menu_edit = tk.Menu(self.menu, tearoff=False) # file menu looks like #To open a new file self.menu_file.add_command(label='New', accelerator='Ctrl+N', command=self.new_file) #To open already existing file. self.menu_file.add_command(label='Open...', accelerator='Ctrl+O', command=self.open_file) #To save the current file self.menu_file.add_command(label='Save', accelerator='Ctrl+S', command=self.save_file) #To save an existing file under new name self.menu_file.add_command(label='Save As...', accelerator='Ctrl+Shift+S', command=self.save_file_as) #To Exit current file or loation. self.menu_file.add_command(label='Exit', accelerator='Alt+F4', command=self.quit_App) # edit menu looks like #To give a Feature of undo and Redo. self.menu_edit.add_command(label='Redo', accelerator='Ctrl+Y', command=self.redo_edit) self.menu_edit.add_command(label='Undo', accelerator='Ctrl+Z', command=self.undo_edit) #To give a feature of cut,copy and Paste. self.menu_edit.add_command(label='Cut', accelerator='Ctrl+X', command=self.text_cut) self.menu_edit.add_command(label='Copy', accelerator='Ctrl+C', command=self.text_copy) self.menu_edit.add_command(label='Paste', accelerator='Ctrl+V', command=self.text_paste) #To give the feature of finding something and/or replacing it. self.menu_edit.add_command(label='Find', accelerator='Ctrl+F', command=self.ask_find_next) self.menu_edit.add_command(label='Find and Replace', accelerator='Ctrl+H', command=self.ask_find_replace) #To get the current time and date at the begining of cursor. self.menu_edit.add_command(label='Time/Date', accelerator='F5', command=self.get_datetime) # code to add cascading menus to main menu self.menu.add_cascade(label='File', menu=self.menu_file) self.menu.add_cascade(label='Edit', menu=self.menu_edit) # how to setup text widget self.text_frame = tk.Frame(self) self.text = ScrolledText(self.text_frame, wrap=tk.WORD, font='-size 20', undo=True, maxundo=10, autoseparator=True, blockcursor=False, padx=5, pady=10) # set default tab size to 4 characters self.font = tkfont.Font(family='Courier New', size=12, weight=tkfont.NORMAL, slant=tkfont.ROMAN, underline=False, overstrike=False) self.text.configure(font=self.font) tab_width = self.font.measure(' ' * 4) self.text.configure(tabs=(tab_width,)) self.text.insert(tk.END, self.file.read_text() if self.file.is_file() else '') # packing up all widget to screen self.text.pack(fill=tk.BOTH, expand=tk.YES) self.text_frame.pack(fill=tk.BOTH, expand=tk.YES) # adding up status bar self.status_bar = StatusBar(self, self.text) # this is the final setup self.update_title() #self.eval('tk::PlaceWindow . center') self.deiconify() # -------------defining FILE MENU starts-------------------------------------- def new_file(self, event=None): """Create a new file""" # check for content change before opening new file self.confirm_changes() # reset text widget self.text.delete(1.0, tk.END) self.file = pathlib.Path.cwd() / 'Untitled_notepad.txt' self.update_title() def open_file(self, event=None): """Open an existing file""" # check for content change before opening new file self.confirm_changes() # open new file file = filedialog.askopenfilename( initialdir=self.file.parent, **self.file_defaults) if file: self.text.delete(1.0, tk.END) # delete existing content self.file = pathlib.Path(file) self.text.insert(tk.END, self.file.read_text()) self.update_title() self.status_bar.update_status() def save_file(self, event=None): """Save the currently open file""" if self.file.name == 'Untitled_notepad.txt': file = filedialog.asksaveasfilename( initialfile=self.file, **self.file_defaults) self.file = pathlib.Path(file) if file else self.file self.file.write_text(self.text.get(1.0, tk.END)) self.update_title() def save_file_as(self, event=None): """Save the currently open file with a different name or location""" file = filedialog.asksaveasfilename( initialdir=self.file.parent, **self.file_defaults) if file: self.file = pathlib.Path(file) self.file.write_text(self.text.get(1.0, tk.END)) self.update_title() def confirm_changes(self): """Check to see if content has changed from original file; if so, confirm save""" if self.file.is_file(): original = self.file.read_text() current = self.text.get(1.0, tk.END) if original != current: confirm = messagebox.askyesno( message="Save current file changes?") if confirm: self.save_file() # new unsaved document with content is prompted to save elif self.text.count(1.0, tk.END)[0] > 1: confirm = messagebox.askyesno(message="Save current document?") if confirm: self.save_file() def update_title(self): """Update the title with the file name""" self.title(self.file.name + " - Notepad") def quit_App(self): """Quit application after checking for user changes""" self.confirm_changes() self.destroy() #-----------------FILE Menu definition Ends-------------------------------- #-----------------EDIT MENU definition starts------------------------------ def undo_edit(self): """Undo the last edit in the stack""" try: self.text.edit_undo() except tk.TclError: pass def redo_edit(self): """Redo the last edit in the stack""" try: self.text.edit_redo() except tk.TclError: pass def text_copy(self): """Append selected text to the clipboard""" selected = self.text.get(tk.SEL_FIRST, tk.SEL_LAST) self.text.clipboard_clear() self.text.clipboard_append(selected) def text_paste(self): """Paste clipboard text into text widget at cursor""" self.text.insert(tk.INSERT, self.text.clipboard_get()) def text_cut(self): """Cut selected text and append to clipboard""" selected = self.text.get(tk.SEL_FIRST, tk.SEL_LAST) self.text.delete(tk.SEL_FIRST, tk.SEL_LAST) self.text.clipboard_clear() self.text.clipboard_append(selected) def quit_application(self, event=None): """Quit application after checking for user changes""" self.confirm_changes() self.destroy() def ask_find_next(self, event=None): """Create find next popup widget""" self.findnext = Find(self, self.text) def ask_find_replace(self, event=None): """Create replace popup widget""" self.findreplace = Replace(self, self.text) def get_datetime(self, event=None): """insert date and time at cursor position""" self.text.insert(tk.INSERT, datetime.datetime.now().strftime("%c"))
class Gui(): def __init__(self): self.file_path = None self.simulation_data = None # A ScriptOutput object self.root = tk.Tk() self.root.protocol("WM_DELETE_WINDOW", self.file_quit) self.set_title() self.scriptLabel = None self.scriptField = None self._create_widgets() self._assign_accelerators() self.root.mainloop() def _create_widgets(self): # The frame containing the widgets frame = tk.Frame(self.root) # The menu bar menu_bar = tk.Menu(self.root, tearoff=0) # The File menu file_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window file_menu.add_command(label="New", underline=0, command=self.file_new) # , accelerator="Ctrl+N") file_menu.add_command( label="Open...", underline=0, command=self.file_open) # , accelerator="Ctrl+O") file_menu.add_command( label="Save", underline=0, command=self.file_save) # , accelerator="Ctrl+S") file_menu.add_command(label="Save As...", underline=1, command=self.file_save_as) file_menu.add_separator() file_menu.add_command(label="Exit", underline=1, command=self.file_quit) menu_bar.add_cascade(label="File", underline=0, menu=file_menu) # The Run menu run_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window run_menu.add_command(label="Simulate and Plot", underline=0, command=self.simulate, accelerator="F5") run_menu.add_command(label="Plot", underline=0, command=self.plot) menu_bar.add_cascade(label="Run", underline=0, menu=run_menu) # The Edit menu edit_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window edit_menu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl+Z") edit_menu.add_command(label="Redo", underline=0, command=self.redo, accelerator="Ctrl+Y") menu_bar.add_cascade(label="Edit", underline=0, menu=edit_menu) self.root.config(menu=menu_bar) # The label lbltxt = "Place your script in the box below or open a text file" # lbltxt = "Simulate: F5, Open: Ctrl+O, Save: Ctrl+S, New: Ctrl+N" scriptLabel = tk.Label(frame, text=lbltxt) scriptLabel.pack(side="top", anchor="w") # The Text widget self.scriptField = ScrolledText(frame) self.scriptField.pack(side="top", fill=BOTH, expand=YES) self.scriptField.config(undo=True) self.scriptField.focus_set() # self.scriptField.config( # borderwidth=0, # font="{Lucida Sans Typewriter} 12", # foreground="green", # background="black", # insertbackground="white", # cursor # selectforeground="green", # selection # selectbackground="#008000", # wrap=tk.WORD, # use word wrapping # width=64, # undo=True, # Tk 8.4 # ) # The Quit button # quitButton = tk.Button(frame, text="Quit", command=self.quit) # quitButton.pack(side="right") # The Close All button closefigButton = tk.Button(frame, text="Close All Figures", command=self.close_figs) closefigButton.pack(side="right") # The Simulate button simButton = tk.Button(frame, text="Simulate and Plot", command=self.simulate) simButton.pack(side="left") # The Plot button plotButton = tk.Button(frame, text="Plot", command=self.plot) plotButton.pack(side="left") frame.pack(fill=BOTH, expand=YES) def simulate(self, event=None): try: script = self.scriptField.get("1.0", "end-1c") script_obj = LsScript.LsScript(script) self.simulation_data = script_obj.run() script_obj.postproc(self.simulation_data) except Exception as ex: self.handle_exception(ex) def plot(self): try: if self.simulation_data is None: raise LsGuiException("No simulation data to plot.") script = self.scriptField.get("1.0", "end-1c") script_obj = LsScript.LsScript(script) script_obj.postproc(self.simulation_data) except Exception as ex: self.handle_exception(ex) def close_figs(self): plt.close("all") def handle_exception(self, ex): # err_msg = ex.args[0] err_msg = str(ex) # if len(ex.args) == 2: # err_msg = "{0} {1}".format(err_msg, ex.args[1]) # # err_msg = err_msg + ex.args[1] messagebox.showerror("Error", err_msg) print(traceback.format_exc()) # def file_open(self): # filename = filedialog.askopenfilename() # # filename = "C:/Python/Python36-32/_Markus/scriptexempel2.txt" # XXX # file = open(filename, "r") # self.scriptField.delete("1.0", "end-1c") # self.scriptField.insert("1.0", file.read()) # self.scriptField.mark_set("insert", "1.0") # file.close() # Make sure you close the file when done def save_changes(self): if self.scriptField.edit_modified(): msg = "This document has been modified. Do you want to save changes?" save_changes = messagebox.askyesnocancel("Save?", msg) if save_changes is None: # Cancel return False elif save_changes is True: # Yes self.file_save() return True def file_new(self, event=None): save_changes = self.save_changes() if not save_changes: return self.scriptField.delete(1.0, "end") self.scriptField.edit_modified(False) self.scriptField.edit_reset() self.file_path = None self.set_title() def file_open(self, event=None): # , filepath=None): save_changes = self.save_changes() if not save_changes: return # XXX initialdir = '.' if os.path.isdir('/home/markus/Dropbox/'): initialdir = '/home/markus/Dropbox/LearningSimulator/Scripts' filepath = filedialog.askopenfilename(filetypes=FILETYPES, initialdir=initialdir) if filepath is not None and len(filepath) != 0: with open(filepath, encoding="utf-8") as f: file_contents = f.read() # Set current text to file contents self.scriptField.delete(1.0, "end") self.scriptField.insert(1.0, file_contents) self.scriptField.edit_modified(False) self.scriptField.mark_set("insert", "1.0") self.file_path = filepath self.set_title() def file_save(self, event=None): self.file_save_as(filepath=self.file_path) def file_save_as(self, filepath=None, event=None): if filepath is None: filepath = filedialog.asksaveasfilename(filetypes=FILETYPES) if len( filepath ) == 0: # Empty tuple or empty string is returned if cancelled return # "cancelled" try: with open(filepath, 'wb') as f: text = self.scriptField.get(1.0, "end-1c") f.write(bytes(text, 'UTF-8')) self.scriptField.edit_modified(False) self.file_path = filepath self.set_title() return # "saved" except IOError as e: self.handle_exception(e) return # "cancelled" def file_quit(self, event=None): save_changes = self.save_changes() if not save_changes: return self.close_figs() self.root.destroy() # sys.exit(0) def set_title(self, event=None): if self.file_path is not None: # title = os.path.basename(self.file_path) title = os.path.abspath(self.file_path) else: title = "Untitled" self.root.title(title + " - " + TITLE) def undo(self, event=None): try: self.scriptField.edit_undo() except Exception as e: self.handle_exception(e) return "break" def redo(self, event=None): self.scriptField.edit_redo() return "break" def _assign_accelerators(self): # self.scriptField.bind("<Control-n>", self.file_new) # self.scriptField.bind("<Control-N>", self.file_new) # self.scriptField.bind("<Control-o>", self.file_open) # self.scriptField.bind("<Control-O>", self.file_open) # self.scriptField.bind("<Control-S>", self.file_save) # self.scriptField.bind("<Control-s>", self.file_save) self.scriptField.bind("<Control-y>", self.redo) self.scriptField.bind("<Control-Y>", self.redo) self.scriptField.bind("<Control-z>", self.undo) self.scriptField.bind("<Control-Z>", self.undo) # self.root.bind_class("Text", ",<Control-z>", self.undo) # self.root.bind_class("Text", ",<Control-Z>", self.undo) # self.root.bind_class("Text", ",<Control-y>", self.redo) # self.root.bind_class("Text", ",<Control-Y>", self.redo) self.scriptField.bind("<F5>", self.simulate)
class Window(Listbox): # Initializes the variables and settings for the project. Finally # executes the create_menu for the menu bar, and the create_notepad # for the text window def __init__(self, master, **kw): # Sets master, or root super().__init__(master, **kw) self.master = master # Set some variables self.current_file_path = '' self.current_file_text = '' self.is_saved = True # Set up the context menu and the text box self.context_popup_menu = Menu(self.master, tearoff=0) self.text_window = ScrolledText(self.master, undo=True) self.text_window.focus() self.user_data = self.text_window.get('1.0', END + '-1c') # Name the window, icon, and start the create functions self.master.title(NAME) # self.master.iconbitmap('./tk/images/icon.ico') self.initiate_shortcuts() self.create_menu() self.create_notepad() self.create_context_menu() # Creates the context menu def create_context_menu(self): # Adds a command for button, separator for separator self.context_popup_menu.add_command(label="Undo", command=lambda: self.undo()) self.context_popup_menu.add_command(label="Redo", command=lambda: self.redo()) self.context_popup_menu.add_separator() self.context_popup_menu.add_command( label="Cut", command=lambda: self.text_window.event_generate("<<Cut>>")) self.context_popup_menu.add_command( label="Copy", command=lambda: self.text_window.event_generate("<<Copy>>")) self.context_popup_menu.add_command( label="Paste", command=lambda: self.text_window.event_generate("<<Paste>>")) self.context_popup_menu.add_separator() self.context_popup_menu.add_command(label="Delete", command=lambda: self.clear()) self.context_popup_menu.add_separator() self.context_popup_menu.add_command(label="Select All", command=lambda: self.select_all()) # Creates the top bar menu def create_menu(self): # Creating menu bar and adding it to master menu_bar = Menu(self.master) text = self.text_window # Telling root that menu_bar is the Window's menu self.master.config(menu=menu_bar) # Creating the File menu dropdown file_menu = Menu(menu_bar, tearoff=False) file_menu.add_command(label="New Document...", command=self.new_file, accelerator="Ctrl+N") file_menu.add_command(label="Open Document...", command=self.open_file, accelerator="Ctrl+O") file_menu.add_command(label="Save...", command=self.save_file, accelerator="Ctrl+S") file_menu.add_command(label="Save as...", command=self.save_as_file, accelerator="Ctrl+Shift+S") file_menu.add_separator() file_menu.add_command(label="Quit", command=self.exit, accelerator="Ctrl+Q") # Adding it to the menu_bar menu_bar.add_cascade(label="File", menu=file_menu, underline=0) # Creating the Edit menu dropdown edit_menu = Menu(menu_bar, tearoff=False) edit_menu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z") edit_menu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y") edit_menu.add_separator() edit_menu.add_command(label="Cut", command=lambda: text.event_generate("<<Cut>>"), accelerator="Ctrl+X") edit_menu.add_command(label="Copy", command=lambda: text.event_generate("<<Copy>>"), accelerator="Ctrl+C") edit_menu.add_command(label="Paste", command=lambda: text.event_generate("<<Paste>>"), accelerator="Ctrl+V") edit_menu.add_separator() edit_menu.add_command(label="Select All", command=lambda: self.select_all(), accelerator="Ctrl+A") edit_menu.add_command(label="Delete", command=self.clear, accelerator="Del") # edit_menu.add_separator() # edit_menu.add_command(label="Settings...", command=settings, accelerator="Ctrl+S") # Adding it to the menu_bar menu_bar.add_cascade(label="Edit", menu=edit_menu) # Creating the Help menu help_menu = Menu(menu_bar, tearoff=False) help_menu.add_command(label="About...", command=about) # Adding it to the menu_bar menu_bar.add_cascade(label="Help", menu=help_menu) # Bind the shortcuts to their specified functions def initiate_shortcuts(self): self.master.bind("<KeyRelease>", lambda event: self.on_text_change()) self.master.bind("<Control-n>", lambda event: self.new_file()) self.master.bind("<Control-o>", lambda event: self.open_file()) self.master.bind("<Control-s>", lambda event: self.save_file()) self.master.bind("<Control-Shift-s>", lambda event: self.save_as_file()) self.master.bind("<Control-q>", lambda event: self.exit()) self.master.bind("<Control-z>", lambda event: self.undo()) self.master.bind("<Control-y>", lambda event: self.redo()) self.text_window.bind("<Control-a>", lambda event: self.select_all()) # self.master.bind("<Control-s>", lambda event: settings()) self.master.bind("<Button-3>", lambda event: self.right_click_popup(event)) # Display context menu popup def right_click_popup(self, event): try: # Used +45 and + 12 to corner it self.context_popup_menu.tk_popup(event.x_root + 45, event.y_root + 12, 0) finally: self.context_popup_menu.grab_release() # Scaling the text_window to fit the screen def create_notepad(self): self.text_window.pack(fill="both", expand=True) # Returns the value of the text field def get_text_data(self): return self.text_window.get('1.0', END + '-1c') # Clears the text off the screen, resets the variables def clear_text(self): self.text_window.delete('1.0', END) self.current_file_path = '' self.current_file_text = '' # Called when typing, sets the is_saved variable def on_text_change(self): # If the text in the textbox is equal to the saved text in the variable # This is used when opening a file, changing something, then undoing that change if self.get_text_data() == self.current_file_text: self.is_saved = True else: # If the saved file exists or is valid if os.path.isfile(self.current_file_path): # Open the file, save it's data to this_file with open(self.current_file_path, "r") as f: this_file = f.read() # If this_file is equal to the same text in the textbox # Used if no changes were made, and if they were, set to False self.is_saved = True if this_file == self.get_text_data( ) else False else: # If the data is not equal to variable, and no file, then changes # must have been made self.is_saved = False # MENU CONTROL FUNCTIONS # Clear current selection, erase the current file if saved def new_file(self): # If it's saved, clear it and set the file to saved if self.is_saved is True: self.clear_text() self.is_saved = True else: # Popup the saved popup popup_value = is_saved_popup() if popup_value == "yes": # Save the file, clear it and set the is_saved to True if self.save_file() is True: self.clear_text() self.is_saved = True elif popup_value == "no": # Don't save the file, but clear it and set the is_saved to True self.clear_text() self.is_saved = True else: # Something went wrong print("Error: new_file error") # Open a file if the current file is saved, then insert new file data def open_file(self): # If file is saved, open the open_file window if self.is_saved is True: self.open_file_popup() else: # Save the file, if it's saved, open the open_file window popup_value = is_saved_popup() if popup_value == "yes": if self.save_file() is True: self.is_saved = True self.open_file_popup() # Open the open_file window elif popup_value == "no": self.open_file_popup() else: # An error occurred print("Error: open_file error") # The function that displays the open_file popup def open_file_popup(self): # Gets old data from current file old_file = self.current_file_path # Opens the file location, stores it in file_name file_name = filedialog.askopenfilename( title="Open", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) # If a file was actually selected, open it if file_name is not '': with open(file_name) as f: data = f.read() # Clear current text self.clear_text() # Set the path variable of the new file self.current_file_path = file_name if os.path.isfile( file_name) else old_file # Add the file data to the text_box self.text_window.insert(INSERT, data) # Add the file data to the variable self.current_file_text = data # is_saved is True self.is_saved = True # Save file, if file exists, overwrite it, otherwise, call save_as_file function def save_file(self): # If the file path exists if os.path.isfile(self.current_file_path): # Stores the current text data into the variable self.current_file_text = self.get_text_data() # Saves the data to the existing file (overwriting) with open(self.current_file_path, "w") as f: return True if f.writelines( self.get_text_data()) is True else False else: # File doesn't exist, call save_as_file if self.save_as_file() is True: return True # Saves file with asksaveasfile to open a save as window. def save_as_file(self): # Gets old file path old_file = self.current_file_path # Opens save_as window file_name = filedialog.asksaveasfilename( title="Save As", defaultextension=".txt", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) # Set current file path self.current_file_path = old_file if file_name is None else file_name # If the file_path already exists if os.path.isfile(self.current_file_path): # Copy the current text to the variable self.current_file_text = self.get_text_data() # Writes to the named file with open(self.current_file_path, "w") as f: f.writelines(self.get_text_data()) return True else: # A file wasn't selected if file_name is '': print("Error: File is none") return False # Create a new file to store the data self.current_file_text = self.get_text_data() with open(file_name, 'w'): pass self.is_saved = True return True # Exit override command def exit(self): # If the file is saved, exit if self.is_saved is True: self.master.quit() else: # If the file is not saved, call the saved_popup popup_value = is_saved_popup() if popup_value == "yes": # Save and then quit if self.save_file() is True: self.is_saved = True self.quit() elif popup_value == "no": # Don't save, just quit self.master.quit() else: # An error occurred print("Error: open_file error") # Undo last action def undo(self): self.text_window.edit_undo() # Redo last action def redo(self): self.text_window.edit_redo() # Clear (delete) the selected text def clear(self): self.text_window.delete(SEL_FIRST, SEL_LAST) self.text_window.update() # Select the selected text (without new line) def select_all(self): self.text_window.tag_add(SEL, "1.0", END + '-1c') self.text_window.mark_set(INSERT, "1.0") self.text_window.see(INSERT) return 'break'
label="SHA512", command=lambda: checksum("sha512", data=(e.get(1.0, END)).encode("utf-8"))) filemenu.add_separator() filemenu.add_command(label="Close File", command=close) filemenu.add_command(label="Exit", command=lambda: __quit(1), accelerator="Ctrl+Q") menubar.add_cascade(label="File", menu=filemenu) # EDIT MENU editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Undo", command=lambda: e.edit_undo(), accelerator="Ctrl+Z") editmenu.add_command(label="Redo", command=lambda: e.edit_redo(), accelerator="Ctrl+Y") editmenu.add_separator() editmenu.add_command(label="Cut", command=cut, accelerator="Ctrl+X") editmenu.add_command(label="Copy", command=copy, accelerator="Ctrl+C") editmenu.add_command(label="Paste", command=paste, accelerator="Ctrl+V") editmenu.add_command(label="Delete", command=delete, accelerator="Del") editmenu.add_separator() editmenu.add_command(label="Goto", command=lambda: goto(1), accelerator="Ctrl+G") editmenu.add_separator() editmenu.add_command(label="Select all", command=select_all, accelerator="Ctrl+A") editmenu.add_command(label="Delete all",
class meta_vwr(): def __init__(self, master, x=None, y=None ): self.master_app = master self.meta_vwr_root = tki.Toplevel() self.meta_vwr_root.title( 'metadata editor' ) self.meta_vwr_root.protocol( "WM_DELETE_WINDOW", self.__del__ ) scrn_w = self.master_app.root.winfo_screenwidth() width = scrn_w/3 if( x is None ): x = (scrn_w/3) - (width/3) scrn_h = self.master_app.root.winfo_screenheight() height = scrn_w/3 if( y is None ): y = (scrn_h/3) - (height/3) self.meta_vwr_root.geometry('%dx%d+%d+%d' % (width, height, x, y)) self.meta_vwr_frame = tki.Frame( self.meta_vwr_root ) self.meta_vwr_frame.pack( side='bottom', fill='both', expand=True ) self.textPad = ScrolledText( self.meta_vwr_frame, wrap='word', undo=True ) self.textPad['font'] = ('consolas', '12') self.textPad.pack( side='left', fill='both', expand=True ) self.textPad.config( state='normal' ) self.textPad.delete('1.0', tki.END ) self.textPad.insert( 1.0, self.master_app.doc.meta ) self.old_metadata = self.master_app.doc.meta self.meta_vwrmenu = tki.Menu( self.meta_vwr_root, tearoff=0 ) self.meta_vwr_root.config( menu=self.meta_vwrmenu ) self.meta_vwrmenu.add_command( label="Undo", underline=1, command=self.undo_handler ) self.meta_vwrmenu.add_command( label="Redo", underline=1, command=self.redo_handler ) self.meta_vwrmenu.add_command( label="Delete All", underline=1, command=self.delete_all_handler ) self.meta_vwrmenu.add_command( label="Cancel", underline=1, command=self.cancel_handler ) self.master_app.meta_vwr = self print( 'init meta_vwr master_meta_vwr is {0}'.format( self.master_app.meta_vwr )) self.meta_vwr_root.update_idletasks() self.meta_vwr_root.mainloop() def __del__( self ): self.meta_vwr_root.update_idletasks() self.meta_vwr_root.quit() self.meta_vwr_root.destroy() self.master_app.meta_vwr = None print( 'deleted meta vwr master meta_vwr is {0}'.format( self.master_app.meta_vwr )) def undo_handler( self, event=None ): self.textPad.edit_undo() def redo_handler( self, event=None ): self.textPad.edit_redo() def delete_all_handler( self ): self.textPad.delete('1.0', tki.END ) def cancel_handler( self ): self.master_app.doc.meta = self.textPad.get( '1.0', tki.END + '-1c' ) self.__del__() def refresh_handler( self ): print( 'meta_vwr refresh master_app_meta_vwr={0}'.format( self.master_app.meta_vwr )) self.meta_vwr_root.lift() self.meta_vwr_root.update_idletasks()
class Main(object): def __init__(self, root_): self.root = root_ self.file_path = None self.root.title("Proyecto final Inteligencia Artifical II") # Images and title self.title_label = Label( root, text="UNIVERSIDAD DE LAS FUERZAS ARMADAS ESPE") self.title_label.grid(row=0, column=0, columnspan=2) img = Image.open("logo.png") img = img.resize((250, 70), Image.ANTIALIAS) self.image = ImageTk.PhotoImage(img) self.image_label = Label(root, image=self.image) self.image_label.grid(row=1, column=0, columnspan=2) self.rule_editor_label = Label(root, text="Hechos: ", padx=10, pady=1) self.rule_editor_label.grid(sticky="W", row=2, column=0, columnspan=2, pady=3) # Create rule editor where we can edit the rules we want to enter: self.rule_editor = ScrolledText(root, width=100, height=30, padx=10, pady=10) self.rule_editor.grid(sticky=W + E, row=3, column=0, columnspan=2, padx=10) self.rule_editor.config(wrap="word", undo=True) self.rule_editor.focus() # Create a query label: self.query_label = Label(root, text="Prolog Query:", padx=10, pady=1) self.query_label.grid(sticky=W, row=4, column=0, columnspan=2, pady=3) # Create the Prolog query editor we'll use to query our rules: self.query_editor = Text(root, width=77, height=2, padx=10, pady=10) self.query_editor.grid(sticky=W, row=5, column=0, pady=3, padx=10) self.query_editor.config(wrap="word", undo=True) # Create a run button which runs the query against our rules and outputs the # results in our solutions text box / editor. self.run_button = Button( root, text="Find Query Solutions", height=2, width=20, command=self.run_query, ) self.run_button.grid(sticky=E, row=5, column=1, pady=3, padx=10) # Create a solutions label self.solutions_label = Label(root, text="Query Solutions:", padx=10, pady=1) self.solutions_label.grid(sticky="W", row=6, column=0, columnspan=2, padx=10, pady=3) # Create a text box which we'll use to display our Prolog query solutions: self.solutions_display = ScrolledText(root, width=100, height=5, padx=10, pady=10) self.solutions_display.grid(row=7, column=0, columnspan=2, padx=10, pady=7) # Finally, let's create the file menu self.menu_bar = self.create_file_menu() def add_new_fact(self): pass def load_exercise_two(self): pass def load_exercise_five(self): pass def create_file_menu(self): """Create a menu which will allow us to open / save our Prolog rules, run our query, and exit our editor interface """ menu_bar = Menu(root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="Abrir", underline=1, command=self.open_file) file_menu.add_separator() file_menu.add_command(label="Save", underline=1, command=self.save_file) file_menu.add_command(label="Save As...", underline=5, command=self.save_file_as) file_menu.add_separator() file_menu.add_command(label="Run", underline=1, command=self.run_query) file_menu.add_separator() file_menu.add_command(label="Exit", underline=2, command=self.root.destroy) menu_bar.add_cascade(label="File", underline=0, menu=file_menu) self.root.config(menu=menu_bar) return menu_bar def run_query(self): """Interpret the entered rules and query and display the results in the solutions text box """ # Delete all of the text in our solutions display text box self.solutions_display.delete("1.0", END) self.set_busy() # Fetch the raw rule / query text entered by the user rules_text = self.rule_editor.get(1.0, "end-1c") query_text = self.query_editor.get(1.0, "end-1c") # Create a new solver so we can try to query for solutions. try: solver = Solver(rules_text) except Exception as e: self.handle_exception("Error processing prolog rules.", str(e)) return # Attempt to find the solutions and handle any exceptions gracefully try: solutions = solver.find_solutions(query_text) except Exception as e: self.handle_exception("Error processing prolog query.", str(e)) return # If our query returns a boolean, we simply display a 'Yes' or a 'No' # depending on its value if isinstance(solutions, bool): self.solutions_display.insert(END, "Yes." if solutions else "No.") # Our solver returned a map, so we display the variable name to value mappings elif isinstance(solutions, dict): self.solutions_display.insert( END, "\n".join( "{} = {}" # If our solution is a list contining one item, we show that # item, otherwise we display the entire list .format(variable, value[0] if len(value) == 1 else value) for variable, value in solutions.items() ), ) else: # We know we have no matching solutions in this instance so we provide # relevant feedback self.solutions_display.insert(END, "No solutions found.") self.set_not_busy() def handle_exception(self, error_message, exception=""): """Handle the exception by printing an error message as well as exception in our solution text editor / display """ self.solutions_display.insert(END, error_message + "\n") self.solutions_display.insert(END, str(exception) + "\n") self.set_not_busy() def set_rule_editor_text(self, text): self.rule_editor.delete(1.0, "end") self.rule_editor.insert(1.0, text) self.rule_editor.edit_modified(False) def set_busy(self): # Show a busy cursor and update the UI self.root.config(cursor="watch") self.root.update() def set_not_busy(self): # Show a regular cursor self.root.config(cursor="") def open_file(self, file_path=None): # Open a a new file dialog which allows the user to select a file to open if file_path is None: file_path = filedialog.askopenfilename() if is_file_path_selected(file_path): file_contents = get_file_contents(file_path) # Set the rule editor text to contain the selected file contents self.set_rule_editor_text(file_contents) self.file_path = file_path def save_file(self): """If we have specified a file path, save the file - otherwise, prompt the user to specify the file location prior to saving the file """ if self.file_path is None: result = self.save_file_as() else: result = self.save_file_as(file_path=self.file_path) return result def write_editor_text_to_file(self, file): editor_text = self.rule_editor.get(1.0, "end-1c") file.write(bytes(editor_text, "UTF-8")) self.rule_editor.edit_modified(False) def save_file_as(self, file_path=None): # If there is no file path specified, prompt the user with a dialog which # allows him/her to select where they want to save the file if file_path is None: file_path = filedialog.asksaveasfilename(filetypes=( ("Text files", "*.txt"), ("Prolog files", "*.pl *.pro"), ("All files", "*.*"), )) try: # Write the Prolog rule editor contents to the file location with open(file_path, "wb") as file: self.write_editor_text_to_file(file) self.file_path = file_path return "saved" except FileNotFoundError: return "cancelled" def undo(self): self.rule_editor.edit_undo() def redo(self): self.rule_editor.edit_redo()
class Application(tkinter.Tk): def __init__(self): """Initialize widgets, methods.""" tkinter.Tk.__init__(self) self.grid() fontoptions = families(self) font = Font(family="Verdana", size=10) menubar = tkinter.Menu(self) fileMenu = tkinter.Menu(menubar, tearoff=0) editMenu = tkinter.Menu(menubar, tearoff=0) fsubmenu = tkinter.Menu(editMenu, tearoff=0) ssubmenu = tkinter.Menu(editMenu, tearoff=0) # adds fonts to the font submenu and associates lambda functions for option in fontoptions: fsubmenu.add_command(label=option, command = lambda: font.configure(family=option)) # adds values to the size submenu and associates lambda functions for value in range(1,31): ssubmenu.add_command(label=str(value), command = lambda: font.configure(size=value)) # adds commands to the menus menubar.add_cascade(label="File",underline=0, menu=fileMenu) menubar.add_cascade(label="Edit",underline=0, menu=editMenu) fileMenu.add_command(label="New", underline=1,command=self.new, accelerator="Ctrl+N") fileMenu.add_command(label="Open", command=self.open, accelerator="Ctrl+O") fileMenu.add_command(label="Save", command=self.save, accelerator="Ctrl+S") fileMenu.add_command(label="Exit", underline=1,command=exit, accelerator="Ctrl+Q") editMenu.add_command(label="Copy", command=self.copy, accelerator="Ctrl+C") editMenu.add_command(label="Cut", command=self.cut, accelerator="Ctrl+X") editMenu.add_command(label="Paste", command=self.paste, accelerator="Ctrl+V") editMenu.add_cascade(label="Font", underline=0, menu=fsubmenu) editMenu.add_cascade(label="Size", underline=0, menu=ssubmenu) editMenu.add_command(label="Color", command=self.color) editMenu.add_command(label="Bold", command=self.bold, accelerator="Ctrl+B") editMenu.add_command(label="Italic", command=self.italic, accelerator="Ctrl+I") editMenu.add_command(label="Underline", command=self.underline, accelerator="Ctrl+U") editMenu.add_command(label="Overstrike", command=self.overstrike, accelerator="Ctrl+T") editMenu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z") editMenu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y") self.config(menu=menubar) self.bind_all("<Control-n>", self.new) self.bind_all("<Control-o>", self.open) self.bind_all("<Control-s>", self.save) self.bind_all("<Control-q>", self.exit) self.bind_all("<Control-b>", self.bold) self.bind_all("<Control-i>", self.italic) self.bind_all("<Control-u>", self.underline) self.bind_all("<Control-T>", self.overstrike) self.bind_all("<Control-z>", self.undo) self.bind_all("<Control-y>", self.redo) self.text = ScrolledText(self, state='normal', height=80, wrap='word', font = font, pady=2, padx=3, undo=True) self.text.grid(column=0, row=0, sticky='NSEW') # Frame configuration self.grid_columnconfigure(0, weight=1) self.resizable(True, True) def new(self, *args): """Creates a new window.""" app = Application() app.title('Python Text Editor') app.option_add('*tearOff', False) app.mainloop() def color(self): """Changes selected text color.""" try: (rgb, hx) = tkinter.colorchooser.askcolor() self.text.tag_add('color', 'sel.first', 'sel.last') self.text.tag_configure('color', foreground=hx) except TclError: pass def bold(self, *args): """Toggles bold for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "bold" in current_tags: self.text.tag_remove("bold", "sel.first", "sel.last") else: self.text.tag_add("bold", "sel.first", "sel.last") bold_font = Font(self.text, self.text.cget("font")) bold_font.configure(weight="bold") self.text.tag_configure("bold", font=bold_font) except TclError: pass def italic(self, *args): """Toggles italic for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "italic" in current_tags: self.text.tag_remove("italic", "sel.first", "sel.last") else: self.text.tag_add("italic", "sel.first", "sel.last") italic_font = Font(self.text, self.text.cget("font")) italic_font.configure(slant="italic") self.text.tag_configure("italic", font=italic_font) except TclError: pass def underline(self, *args): """Toggles underline for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "underline" in current_tags: self.text.tag_remove("underline", "sel.first", "sel.last") else: self.text.tag_add("underline", "sel.first", "sel.last") underline_font = Font(self.text, self.text.cget("font")) underline_font.configure(underline=1) self.text.tag_configure("underline", font=underline_font) except TclError: pass def overstrike(self, *args): """Toggles overstrike for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "overstrike" in current_tags: self.text.tag_remove("overstrike", "sel.first", "sel.last") else: self.text.tag_add("overstrike", "sel.first", "sel.last") overstrike_font = Font(self.text, self.text.cget("font")) overstrike_font.configure(overstrike=1) self.text.tag_configure("overstrike", font=overstrike_font) except TclError: pass def undo(self, *args): """Undo function""" try: self.text.edit_undo() except TclError: pass def redo(self, *args): """Redo function""" try: self.text.edit_redo() except TclError: pass def copy(self, *args): """Copy text""" self.clipboard_clear() self.clipboard_append(self.text.selection_get()) def cut(self, *args): """Cut text""" self.copy self.text.delete("sel.first", "sel.last") def paste(self, *args): """Paste text""" insertion = self.selection_get(selection = "CLIPBOARD") self.text.insert(0.0, insertion) def open(self, *args): """Opens a file dialog to open a plain text file.""" filename = tkinter.filedialog.askopenfilename() with open(filename) as f: text = f.read() self.text.delete("1.0", "end") self.text.insert('insert', text) def save(self, *args): try: """Opens a file dialog to save the text in plain text format.""" text = self.text.get("1.0", "end") filename = tkinter.filedialog.asksaveasfilename() with open(filename, 'w') as f: f.write(text) except FileNotFoundError: pass def exit(self, *args): """Exits the program.""" self.quit()
class MY_GUI(): def __init__(self, init_window_name): self.init_window_name = init_window_name self.max1 = "" self.filename = "" #设置窗口 def set_init_window(self): # 设置输入输出框字体 ft = tkFont.Font(family='宋体', size=15) self.init_window_name.title("电子病历标注工具_v1.3 ") #窗口名 #self.init_window_name.geometry('320x160+10+10') #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置 self.init_window_name.geometry('1500x1000+10+10') #self.init_window_name["bg"] = "pink" #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887 #self.init_window_name.attributes("-alpha",0.9) #虚化,值越小虚化程度越高 #标签 self.init_data_label = ttk.Label(self.init_window_name, text="待处理数据") self.init_data_label.grid(row=0, column=0) self.result_data_label = ttk.Label(self.init_window_name, text="输出结果") self.result_data_label.grid(row=0, column=12) self.log_label = ttk.Label(self.init_window_name, text="日志") self.log_label.grid(row=12, column=0) #文本框 self.init_data_Text = ScrolledText(self.init_window_name, width=67, height=35, font=ft) #原始数据录入框 self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10) self.result_data_Text = ScrolledText(self.init_window_name, width=70, height=49, font=ft) #处理结果展示 self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10) self.log_data_Text = Text(self.init_window_name, width=66, height=9) # 日志框 self.log_data_Text.grid(row=13, column=0, columnspan=10) self.init_data_Text.bind("<Button-1>", self.button_start) self.init_data_Text.bind("<ButtonRelease-1>", self.button_end) #按钮 # self.str_trans_to_md5_button = Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,command=self.str_trans_to_md5) # 调用内部方法 加()为直接调用 # self.str_trans_to_md5_button.grid(row=1, column=11) #导入文件按钮 self.input_button = ttk.Button(self.init_window_name, text="导入文件", width=8, command=self.openfile) self.input_button.grid(row=0, column=2) # 输入窗口清空按钮 self.delet_input_button = ttk.Button(self.init_window_name, text="一键清空", width=8, command=self.delet_ofInput) self.delet_input_button.grid(row=0, column=3) #展示窗口清空按钮 self.delet_result_button = ttk.Button(self.init_window_name, text="一键清空", width=8, command=self.delet_ofResult) self.delet_result_button.grid(row=0, column=13) #导出文件按钮 self.output_button = ttk.Button(self.init_window_name, text="导出文件", width=8, command=self.outputfile) self.output_button.grid(row=0, column=14) #标记解剖部位按钮 self.show_button = ttk.Button(self.init_window_name, text="解剖部位", width='8', command=self.show_jpbw) self.show_button.grid(row=2, column=11) # 标记症状描述按钮 self.show_button = ttk.Button(self.init_window_name, text="症状描述", width='8', command=self.show_zzms) self.show_button.grid(row=3, column=11) # 标记独立症状按钮 self.show_button = ttk.Button(self.init_window_name, text="独立症状", width='8', command=self.show_dlzz) self.show_button.grid(row=4, column=11) # 标记药物按钮 self.show_button = ttk.Button(self.init_window_name, text="药物", width='8', command=self.show_yw) self.show_button.grid(row=5, column=11) # 标记手术按钮 self.show_button = ttk.Button(self.init_window_name, text="手术", width='8', command=self.show_ss) self.show_button.grid(row=6, column=11) # 恢复操作按钮 self.recover_button = ttk.Button(self.init_window_name, text="恢复", width='8', command=self.recover) self.recover_button.grid(row=0, column=15) # 标注撤销功能ctrl+z实现 self.back_button = ttk.Button(self.init_window_name, text="撤销", width='8', command=self.backToHistory) self.back_button.grid(row=0, column=16) self.result_data_Text.bind('<Control-Key-z>', self.backToHistory) self.result_data_Text.edit_separator() #功能函数 def str_trans_to_md5(self): src = self.init_data_Text.get(1.0, END).strip().replace("\n", "").encode() #print("src =",src) if src: try: myMd5 = hashlib.md5() myMd5.update(src) myMd5_Digest = myMd5.hexdigest() #print(myMd5_Digest) #输出到界面 self.result_data_Text.delete(1.0, END) self.result_data_Text.insert(1.0, myMd5_Digest) self.write_log_to_Text("INFO:str_trans_to_md5 success") except: self.result_data_Text.delete(1.0, END) self.result_data_Text.insert(1.0, "字符串转MD5失败") else: self.write_log_to_Text("ERROR:str_trans_to_md5 failed") #获取鼠标选中文本 def button_start(self, event): global s s = self.init_data_Text.index('@%s,%s' % (event.x, event.y)) print(event.x, event.y) def button_end(self, event): global e e = self.init_data_Text.index('@%s,%s' % (event.x, event.y)) print(str(e)) #标记解剖部位 def show_jpbw(self): self.result_data_Text.edit_separator() start_index = str(s) start_index = start_index[2:] start_index = int(start_index) end_index = str(e) end_index = end_index[2:] end_index = int(end_index) print(self.init_data_Text.selection_get() + "\t" + "解剖部位" + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + "解剖部位" + "\n") print(self.result_data_Text.get(END)) self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记症状描述 def show_zzms(self, ): self.result_data_Text.edit_separator() start_index = str(s) start_index = start_index[2:] start_index = int(start_index) end_index = str(e) end_index = end_index[2:] end_index = int(end_index) print(self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "症状描述" + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + "症状描述" + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记独立症状 def show_dlzz(self): self.result_data_Text.edit_separator() start_index = str(s) start_index = start_index[2:] start_index = int(start_index) end_index = str(e) end_index = end_index[2:] end_index = int(end_index) print(self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "独立症状" + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + "独立症状" + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记药物 def show_yw(self): self.result_data_Text.edit_separator() start_index = str(s) start_index = start_index[2:] start_index = int(start_index) end_index = str(e) end_index = end_index[2:] end_index = int(end_index) print(self.init_data_Text.selection_get() + "\t" + "药物" + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + "药物" + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记手术 def show_ss(self): self.result_data_Text.edit_separator() start_index = str(s) start_index = start_index[2:] start_index = int(start_index) end_index = str(e) end_index = end_index[2:] end_index = int(end_index) print(self.init_data_Text.selection_get() + "\t" + "手术" + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + "手术" + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() #标注操作撤销功能 def callback(self, event): # 每当有字符插入的时候,就自动插入一个分割符,主要是防止每次撤销的时候会全部撤销 self.result_data_Text.edit_separator() def backToHistory(self): #撤销操作 if len(self.result_data_Text.get('1.0', 'end')) != 0: self.result_data_Text.edit_undo() else: #无字符时不能撤销 return def recover(self): #恢复操作 if len(self.max1) == len(self.result_data_Text.get('1.0', END)): return self.result_data_Text.edit_redo() #输入窗口一键清空功能 def delet_ofInput(self): self.init_data_Text.delete('1.0', 'end') #结果窗口一键清空功能 def delet_ofResult(self): self.result_data_Text.delete('1.0', 'end') #打开文件功能 def openfile(self): fname = filedialog.askopenfilename(title='打开文件', filetypes=[('All Files', '*')]) self.filename = os.path.basename(fname) print(self.filename) f = open(fname, 'r', encoding='utf-8', errors='ignore') #对文本数据存储进数组,方便后续操作 line = f.readline() data_list = [] while line: num = list(map(str, line.split())) data_list.append(num) line = f.readline() f.close() data_array = np.array(data_list) f_contet = data_array self.init_data_Text.insert(END, f_contet) # 导出文件功能 def outputfile(self): if self.filename != "": os.chdir(r'E:\GitTest\untitled\文本标注1.1\Annoation') f = open("ann" + self.filename, 'w', encoding='utf-8', errors='ignore') f.write(self.result_data_Text.get("1.0", "end")) json1 = json.dumps(self.result_data_Text.get("1.0", END)) print(json1) showinfo(title="成功", message="标注文件已导出至Annoation文件夹") else: showinfo(title="错误", message="未找到指定文件") #获取当前时间 def get_current_time(self): current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) return current_time #日志动态打印 def write_log_to_Text(self, logmsg): global LOG_LINE_NUM current_time = self.get_current_time() logmsg_in = str(current_time) + " " + str(logmsg) + "\n" #换行 if LOG_LINE_NUM <= 7: self.log_data_Text.insert(END, logmsg_in) LOG_LINE_NUM = LOG_LINE_NUM + 1 else: self.log_data_Text.delete(1.0, 2.0) self.log_data_Text.insert(END, logmsg_in)
class EditorTab(tk.Frame): def __init__(self, master, filepath: str, new_file=False): tk.Frame.__init__(self, master) self.new_file = new_file self.filepath = filepath self.filename = get_filename(filepath) if not new_file else filepath self.master = master self.modified = False self.text_editor = ScrolledText(self, font=("", 15), undo=True, maxundo=-1, wrap="none") self.text_editor.config(highlightthickness=0, bd=0) self.text_editor.grid(row=0, column=1, sticky=tk.NSEW) self.scrollbar_x = tk.Scrollbar(self, orient=tk.HORIZONTAL, command=self.text_editor.xview) self.scrollbar_x.grid(row=1, column=0, columnspan=2, stick=tk.EW) self.text_editor.configure(xscrollcommand=self.scrollbar_x.set) self.line_nb_canvas = tk.Canvas(self, bg=self.text_editor.cget("bg"), bd=0, highlightthickness=0) self.line_nb_canvas.grid_propagate(False) self.line_nb_canvas.grid(row=0, column=0, sticky=tk.NS) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self.default_file_content = str() @property def id(self) -> str: return str(self) def get(self) -> str: return self.text_editor.get("1.0", "end-1c") @property def lines(self): return self.get().splitlines() def update_lines(self): self.line_nb_canvas.delete("all") font = self.text_editor.cget("font") i = 1 y = 0 while self.text_editor.compare(f"{i}.0", "<", tk.END): dline = self.text_editor.dlineinfo(f"{i}.0") if dline: y = dline[1] else: y = -20 self.line_nb_canvas.create_text(1, y, anchor="ne", text=str(i), font=font, fill=Color(175, 175, 175).hex) i += 1 all_boxes = [ self.line_nb_canvas.bbox(item) for item in self.line_nb_canvas.find_all() ] max_width = (min(box[2] - box[0] for box in all_boxes)) * 4 self.line_nb_canvas.configure(width=max_width + 20) for item in self.line_nb_canvas.find_all(): self.line_nb_canvas.move(item, max_width, 0) def get_filename_from_champion_name(self) -> (str, None): content = self.lines for line in content: if line.startswith(".name"): first_quote = line.find('"') if first_quote == -1: break second_quote = line.find('"', first_quote + 1) if second_quote == -1: break name = line[first_quote + 1:second_quote] if len(name) == 0: break return name.replace(" ", "_").lower() + ".s" return None def open(self) -> bool: if not os.path.isfile(self.filepath): showwarning("An error occurs...", f"Can't open '{self.filepath}'") return False with open(self.filepath, "r") as file: self.default_file_content = file.read() self.text_editor.insert("1.0", self.default_file_content) self.text_editor.edit_reset() self.text_editor.edit_modified(False) self.set_modified_status(False, on_opening=True) return True def save(self) -> bool: if self.new_file: return self.master.save_file_as() self.default_file_content = self.text_editor.get("1.0", "end-1c") with open(self.filepath, "w") as file: file.write(self.default_file_content) self.set_modified_status(False) self.text_editor.edit_modified(False) return True def save_as(self, filepath: str) -> bool: self.master.files_opened[filepath] = self.master.files_opened[ self.filepath] self.master.files_opened.pop(self.filepath) self.filepath = filepath self.filename = get_filename(filepath) self.new_file = False return self.save() def close(self) -> bool: if self.modified: save_file = askyesnocancel( f"{self.filename} - Modifications not saved", "This file was modified and was not saved.\nDo you want to save this file ?" ) if save_file is None: return False if save_file and not self.save(): return False self.master.forget(self.id) self.master.files_opened.pop(self.filepath) return True def undo(self) -> None: try: self.text_editor.edit_undo() except tk.TclError: pass def redo(self) -> None: try: self.text_editor.edit_redo() except tk.TclError: pass def copy_to_clipboard(self, remove_from_editor=False) -> bool: try: txt = self.text_editor.get("sel.first", "sel.last") self.clipboard_clear() self.clipboard_append(txt) if remove_from_editor: self.text_editor.delete("sel.first", "sel.last") except tk.TclError: return False return True def paste_from_clipboard(self) -> None: try: self.text_editor.get("sel.first", "sel.last") except tk.TclError: pass else: self.text_editor.mark_set("insert", "sel.first") self.text_editor.delete("sel.first", "sel.last") self.text_editor.insert("insert", self.clipboard_get()) def check_file_status(self) -> None: actual = self.text_editor.get("1.0", "end-1c") if self.text_editor.edit_modified(): self.text_editor.edit_separator() self.text_editor.edit_modified(False) self.set_modified_status(actual != self.default_file_content) def set_modified_status(self, status: bool, on_opening=False) -> None: self.modified = status if not on_opening: if self.modified and not self.new_file: self.master.tab(self.id, text=self.filename + " - Modified") else: self.master.tab(self.id, text=self.filename) def add(self) -> None: self.master.add(self, text=self.filename) def select(self) -> None: self.master.select(self.id) self.text_editor.focus_set() def set_template(self, name: str, comment: str, author: str) -> None: content = [ line for line in self.lines if not line.startswith(".name") and not line.startswith(".comment") ] header = [ "#", "# {name} champion for CoreWar".format(name=name), "#", "# By {author}".format(author=author), "#", "# {date}".format(date=date.today().strftime("%c")), "#", "" ".name \"{name}\"".format(name=name), ".comment \"{comment}\"".format(comment=comment), "" ] content = header + content self.text_editor.delete("1.0", "end") self.text_editor.insert("1.0", "\n".join(content)) def insert_command(self, cmd: str) -> None: insert = self.text_editor.index(tk.INSERT).split(".") end_of_line = insert[0] + "." + tk.END self.text_editor.insert(end_of_line, "\n" + cmd)
class Editor(): def __init__(self, root): self.root = root self.file_path = None self.root.title('Prolog Interpreter') # Create a rule label self.rule_editor_label = Label(root, text="Prolog Rules: ", padx=10, pady=1) self.rule_editor_label.grid(sticky="W", row=0, column=0, columnspan=2, pady=3) # Create rule editor where we can edit the rules we want to enter: self.rule_editor = ScrolledText(root, width=100, height=30, padx=10, pady=10) self.rule_editor.grid(sticky=W + E, row=1, column=0, columnspan=2, padx=10) self.rule_editor.config(wrap="word", undo=True) self.rule_editor.focus() # Create a query label: self.query_label = Label(root, text="Prolog Query:", padx=10, pady=1) self.query_label.grid(sticky=W, row=2, column=0, columnspan=2, pady=3) # Create the Prolog query editor we'll use to query our rules: self.query_editor = Text(root, width=77, height=2, padx=10, pady=10) self.query_editor.grid(sticky=W, row=3, column=0, pady=3, padx=10) self.query_editor.config(wrap="word", undo=True) # Create a run button which runs the query against our rules and outputs the results in our # solutions text box / editor. self.run_button = Button(root, text='Find Query Solutions', height=2, width=20, command=self.run_query) self.run_button.grid(sticky=E, row=3, column=1, pady=3, padx=10) # Create a solutions label self.solutions_label = Label(root, text="Query Solutions:", padx=10, pady=1) self.solutions_label.grid(sticky="W", row=4, column=0, columnspan=2, padx=10, pady=3) # Create a text box which we'll use to display our Prolog query solutions: self.solutions_display = ScrolledText(root, width=100, height=5, padx=10, pady=10) self.solutions_display.grid(row=5, column=0, columnspan=2, padx=10, pady=7) # Finally, let's create the file menu self.create_file_menu() # Create a menu which will allow us to open / save our Prolog rules, run our query, # and exit our editor interface def create_file_menu(self): self.menu_bar = Menu(root) file_menu = Menu(self.menu_bar, tearoff=0) file_menu.add_command(label="Open...", underline=1, command=self.open_file) file_menu.add_separator() file_menu.add_command(label="Save", underline=1, command=self.save_file) file_menu.add_command(label="Save As...", underline=5, command=self.save_file_as) file_menu.add_separator() file_menu.add_command(label="Run", underline=1, command=self.run_query) file_menu.add_separator() file_menu.add_command(label="Exit", underline=2, command=self.root.destroy) self.menu_bar.add_cascade(label="File", underline=0, menu=file_menu) self.root.config(menu=self.menu_bar) # Show a busy cursor and update the UI def set_busy(self): self.root.config(cursor="watch") self.root.update() # Show a regular cursor def set_not_busy(self): self.root.config(cursor="") # Interpret the entered rules and query and display the results in the solutions text box def run_query(self): # Delete all of the text in our solutions display text box self.solutions_display.delete('1.0', END) self.set_busy() # Fetch the raw rule / query text entered by the user rules_text = self.rule_editor.get(1.0, "end-1c") query_text = self.query_editor.get(1.0, "end-1c") # Create a new solver so we can try to query for solutions. try: solver = Solver(rules_text) except Exception as exception: self.handle_exception("Error processing prolog rules.", exception) return # Attempt to find the solutions and handle any exceptions gracefully try: solutions = solver.find_solutions(query_text) except Exception as exception: self.handle_exception("Error processing prolog query.", exception) return # If our query returns a boolean, we simply display a 'Yes' or a 'No' depending on its value if isinstance(solutions, bool): self.solutions_display.insert(END, 'Yes.' if solutions else 'No.') # Our solver returned a map, so we display the variable name to value mappings elif isinstance(solutions, dict): self.solutions_display.insert( END, "\n".join("{} = {}" # If our solution is a list contining one item, we show that # item, otherwise we display the entire list .format(variable, value[0] if len(value) == 1 else value) for variable, value in solutions.items()) ) else: # We know we have no matching solutions in this instance so we provide relevant feedback self.solutions_display.insert(END, "No solutions found.") self.set_not_busy() # Handle the exception by printing an error message as well as exception in our solution text editor / display def handle_exception(self, error_message, exception=''): self.solutions_display.insert(END, error_message + "\n") self.solutions_display.insert(END, str(exception) + '\n') self.set_not_busy() def is_file_path_selected(self, file_path): return file_path != None and file_path != '' # Return a string containing the file contents of the file located at the specified file path def get_file_contents(self, file_path): with open(file_path, encoding="utf-8") as f: file_contents = f.read() return file_contents def set_rule_editor_text(self, text): self.rule_editor.delete(1.0, "end") self.rule_editor.insert(1.0, text) self.rule_editor.edit_modified(False) def open_file(self, file_path=None): # Open a a new file dialog which allows the user to select a file to open if file_path == None: file_path = filedialog.askopenfilename() if self.is_file_path_selected(file_path): file_contents = self.get_file_contents(file_path) # Set the rule editor text to contain the selected file contents self.set_rule_editor_text(file_contents) self.file_path = file_path # If we have specified a file path, save the file - otherwise, prompt the user to specify the file location # prior to saving the file def save_file(self): if self.file_path == None: result = self.save_file_as() else: result = self.save_file_as(file_path=self.file_path) return result def write_editor_text_to_file(self, file): editor_text = self.rule_editor.get(1.0, "end-1c") file.write(bytes(editor_text, 'UTF-8')) self.rule_editor.edit_modified(False) def save_file_as(self, file_path=None): # If there is no file path specified, prompt the user with a dialog which allows him/her to select # where they want to save the file if file_path == None: file_path = filedialog.asksaveasfilename( filetypes=(('Text files', '*.txt'), ('Prolog files', '*.pl *.pro'), ('All files', '*.*'))) try: # Write the Prolog rule editor contents to the file location with open(file_path, 'wb') as file: self.write_editor_text_to_file(file) self.file_path = file_path return "saved" except FileNotFoundError: return "cancelled" def undo(self, event=None): self.rule_editor.edit_undo() def redo(self, event=None): self.rule_editor.edit_redo()
class Notepad(tk.Tk): """A notepad application""" def __init__(self): super().__init__() self.withdraw() self.iconbitmap('images/Notepad.ico') # check platform & set zoom status platform = self.tk.call('tk', 'windowingsystem') self.wm_state('zoomed') if platform == 'win32' else self.attributes('-zoomed', 1) # file variables self.file = pathlib.Path.cwd() / 'untitled.txt' self.file_defaults = { 'defaultextension': 'txt', 'filetypes': [('Text', ['txt', 'text']), ('All Files', '.*')]} # find search replace variables self.query = None self.matches = None self.findnext = None self.findreplace = None # main menu setup self.menu = tk.Menu(self) self.configure(menu=self.menu) self.menu_file = tk.Menu(self.menu, tearoff=False) self.menu_edit = tk.Menu(self.menu, tearoff=False) self.menu_format = tk.Menu(self.menu, tearoff=False) self.menu_help = tk.Menu(self.menu, tearoff=False) # file menu self.menu_file.add_command(label='New', accelerator='Ctrl+N', command=self.new_file) self.menu_file.add_command(label='Open...', accelerator='Ctrl+O', command=self.open_file) self.menu_file.add_command(label='Save', accelerator='Ctrl+S', command=self.save_file) self.menu_file.add_command(label='Save As...', command=self.save_file_as) self.menu_file.add_separator() self.menu_file.add_command(label='Exit', command=self.quit_application) # edit menu self.menu_edit.add_command(label='Undo', accelerator='Ctrl+Z', command=self.undo_edit) self.menu_edit.add_command(label='Redo', accelerator='Ctrl+Y', command=self.redo_edit) self.menu_edit.add_separator() self.menu_edit.add_command(label='Cut', accelerator='Ctrl+X', command=self.text_cut) self.menu_edit.add_command(label='Copy', accelerator='Ctrl+C', command=self.text_copy) self.menu_edit.add_command(label='Paste', accelerator='Ctrl+V', command=self.text_paste) self.menu_edit.add_separator() self.menu_edit.add_command(label='Find', accelerator='Ctrl+F', command=self.ask_find_next) self.menu_edit.add_command(label='Replace', accelerator='Ctrl+H', command=self.ask_find_replace) self.menu_edit.add_separator() self.menu_edit.add_command(label='Select All', accelerator='Ctrl+A', command=self.select_all) self.menu_edit.add_command(label='Time/Date', accelerator='F5', command=self.get_datetime) # format menu self.wrap_var = tk.IntVar() self.wrap_var.set(True) self.block_var = tk.IntVar() self.block_var.set(False) self.menu_format.add_checkbutton(label='Word Wrap', variable=self.wrap_var, command=self.word_wrap) self.menu_format.add_checkbutton(label='Block Cursor', variable=self.block_var, command=self.block_cursor) self.menu_format.add_separator() self.menu_format.add_command(label='Font...', command=self.ask_font_select) # help menu self.menu_help.add_command(label='View Help', state=tk.DISABLED, command=None) self.menu_help.add_command(label='About Notepad', command=self.about_me) # add cascading menus to main menu self.menu.add_cascade(label='File', menu=self.menu_file) self.menu.add_cascade(label='Edit', menu=self.menu_edit) self.menu.add_cascade(label='Format', menu=self.menu_format) self.menu.add_cascade(label='Help', menu=self.menu_help) # add ribbon menu self.ribbon = Ribbon(self) # setup text text widget self.text_frame = tk.Frame(self) self.text = ScrolledText(self.text_frame, wrap=tk.WORD, font='-size 14', undo=True, maxundo=10, autoseparator=True, blockcursor=False, padx=5, pady=10) # set default tab size to 4 characters self.font = tkfont.Font(family='Courier New', size=12, weight=tkfont.NORMAL, slant=tkfont.ROMAN, underline=False, overstrike=False) self.text.configure(font=self.font) tab_width = self.font.measure(' ' * 4) self.text.configure(tabs=(tab_width,)) self.text.insert(tk.END, self.file.read_text() if self.file.is_file() else '') # pack all widget to screen self.text.pack(fill=tk.BOTH, expand=tk.YES) self.text_frame.pack(fill=tk.BOTH, expand=tk.YES) # add status bar self.status_bar = StatusBar(self, self.text) # general callback binding self.bind("<Control-f>", self.ask_find_next) self.bind("<Control-h>", self.ask_find_replace) self.bind("<F5>", self.get_datetime) # final setup self.update_title() #self.eval('tk::PlaceWindow . center') self.deiconify() #---FILE MENU CALLBACKS------------------------------------------------------------------------ def new_file(self): """Create a new file""" # check for content change before opening new file self.confirm_changes() # reset text widget self.text.delete(1.0, tk.END) self.file = pathlib.Path.cwd() / 'untitled.txt' self.update_title() def open_file(self): """Open an existing file""" # check for content change before opening new file self.confirm_changes() # open new file file = filedialog.askopenfilename(initialdir=self.file.parent, **self.file_defaults) if file: self.text.delete(1.0, tk.END) # delete existing content self.file = pathlib.Path(file) self.text.insert(tk.END, self.file.read_text()) self.update_title() self.status_bar.update_status() def save_file(self): """Save the currently open file""" if self.file.name == 'untitled.txt': file = filedialog.asksaveasfilename(initialfile=self.file, **self.file_defaults) self.file = pathlib.Path(file) if file else self.file self.file.write_text(self.text.get(1.0, tk.END)) def save_file_as(self): """Save the currently open file with a different name or location""" file = filedialog.asksaveasfilename(initialdir=self.file.parent, **self.file_defaults) if file: self.file = pathlib.Path(file) self.file.write_text(self.text.get(1.0, tk.END)) self.update_title() def confirm_changes(self): """Check to see if content has changed from original file; if so, confirm save""" if self.file.is_file(): original = self.file.read_text() current = self.text.get(1.0, tk.END) if original != current: confirm = messagebox.askyesno(message="Save current file changes?") if confirm: self.save_file() # new unsaved document with content is prompted to save elif self.text.count(1.0, tk.END)[0] > 1: confirm = messagebox.askyesno(message="Save current document?") if confirm: self.save_file() def quit_application(self): """Quit application after checking for user changes""" self.confirm_changes() self.destroy() def update_title(self): """Update the title with the file name""" self.title(self.file.name + " - Notepad") #---EDIT MENU CALLBACKS------------------------------------------------------------------------ def undo_edit(self): """Undo the last edit in the stack""" try: self.text.edit_undo() except tk.TclError: pass def redo_edit(self): """Redo the last edit in the stack""" try: self.text.edit_redo() except tk.TclError: pass def text_copy(self): """Append selected text to the clipboard""" selected = self.text.get(tk.SEL_FIRST, tk.SEL_LAST) self.text.clipboard_clear() self.text.clipboard_append(selected) def text_paste(self): """Paste clipboard text into text widget at cursor""" self.text.insert(tk.INSERT, self.text.clipboard_get()) def text_cut(self): """Cut selected text and append to clipboard""" selected = self.text.get(tk.SEL_FIRST, tk.SEL_LAST) self.text.delete(tk.SEL_FIRST, tk.SEL_LAST) self.text.clipboard_clear() self.text.clipboard_append(selected) def ask_find_next(self, event=None): """Create find next popup widget""" self.findnext = Find(self, self.text) def ask_find_replace(self, event=None): """Create replace popup widget""" self.findreplace = Replace(self, self.text) def select_all(self): """Select all text in the text widget""" self.text.tag_add(tk.SEL, '1.0', tk.END) def get_datetime(self, event=None): """insert date and time at cursor position""" self.text.insert(tk.INSERT, datetime.datetime.now().strftime("%c")) #---FORMAT MENU CALLBACKS------------------------------------------------------------------------ def word_wrap(self): """Toggle word wrap in text widget""" w = self.wrap_var.get() if w: self.text.configure(wrap=tk.WORD) else: self.text.configure(wrap=tk.NONE) def block_cursor(self): """Toggle word wrap in text widget""" if self.block_var.get(): self.text.configure(blockcursor=True) else: self.text.configure(blockcursor=False) def ask_font_select(self): """Font selector popup""" f = FontSelector(self) tab_width = self.font.measure(' ' * 4) self.text.configure(tabs=(tab_width,)) #---OTHER-------------------------------------------------------------------------------------- def about_me(self): """Application and license info""" AboutMe(self)
class MY_GUI(): def __init__(self, init_window_name): self.init_window_name = init_window_name self.max1 = "" self.filename = "" self.filePath = "" self.content = "" # self.btns_names=['人名','年龄','毕业院校','工作单位','其他数值'] self.btns_names = ['person', 'birthyear', 'age', 'scho', 'work_loc'] #设置窗口 def set_init_window(self): # 设置输入输出框字体 # ft = tkFont.Font(family='宋体', size=15) ft = tkFont.Font(family='微软雅黑', size=15) self.init_window_name.title("履历命名实体识别") #窗口名 #self.init_window_name.geometry('320x160+10+10') #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置 self.init_window_name.geometry('1500x1000+10+10') #self.init_window_name["bg"] = "pink" #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887 #self.init_window_name.attributes("-alpha",0.9) #虚化,值越小虚化程度越高 #标签 self.init_data_label = Label(self.init_window_name, text="待处理数据") self.init_data_label.grid(row=0, column=0) self.result_data_label = Label(self.init_window_name, text="输出结果") self.result_data_label.grid(row=0, column=12) self.log_label = Label(self.init_window_name, text="日志") self.log_label.grid(row=12, column=0) #文本框 self.init_data_Text = ScrolledText(self.init_window_name, width=67, height=35, font=ft) #原始数据录入框 self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10) self.result_data_Text = ScrolledText(self.init_window_name, width=70, height=49, font=ft) #处理结果展示 self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10) self.log_data_Text = Text(self.init_window_name, width=66, height=9) # 日志框 self.log_data_Text.grid(row=13, column=0, columnspan=10) self.init_data_Text.bind("<Button-1>", self.button_start) self.init_data_Text.bind("<ButtonRelease-1>", self.button_end) #按钮 # self.str_trans_to_md5_button = Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,command=self.str_trans_to_md5) # 调用内部方法 加()为直接调用 # self.str_trans_to_md5_button.grid(row=1, column=11) #导入文件按钮 self.input_button = Button(self.init_window_name, text="导入文件", bg="lightgreen", width=8, command=self.openfile) self.input_button.grid(row=0, column=2) self.input_button = Button(self.init_window_name, text="上一文本", bg="lightgreen", width=8, command=self.openLastfile) self.input_button.grid(row=0, column=5) self.input_button = Button(self.init_window_name, text="下一文本", bg="lightyellow", width=8, command=self.openNextfile) self.input_button.grid(row=0, column=7) # 输入窗口清空按钮 self.delet_input_button = Button(self.init_window_name, text="一键清空", bg="#DB7093", width=8, command=self.delet_ofInput) self.delet_input_button.grid(row=0, column=3) #展示窗口清空按钮 self.delet_result_button = Button(self.init_window_name, text="一键清空", bg="#DB7093", width=8, command=self.delet_ofResult) self.delet_result_button.grid(row=0, column=13) #导出文件按钮 self.output_button = Button(self.init_window_name, text="导出文件", bg="lightgreen", width=8, command=self.outputfile) self.output_button.grid(row=0, column=14) #标记解剖部位按钮 self.show_button = Button(self.init_window_name, text=self.btns_names[0], bg="lightblue", width='8', command=self.show_jpbw) self.show_button.grid(row=2, column=10) # 标记症状描述按钮 self.show_button = Button(self.init_window_name, text=self.btns_names[1], bg="lightyellow", width='8', command=self.show_zzms) self.show_button.grid(row=3, column=10) # 标记独立症状按钮 self.show_button = Button(self.init_window_name, text=self.btns_names[2], bg="lightgreen", width='8', command=self.show_dlzz) self.show_button.grid(row=4, column=10) # 标记药物按钮 self.show_button = Button(self.init_window_name, text=self.btns_names[3], bg="#DB7093", width='8', command=self.show_yw) self.show_button.grid(row=5, column=10) # 标记手术按钮 self.show_button = Button(self.init_window_name, text=self.btns_names[4], bg="lightpink", width='8', command=self.show_ss) self.show_button.grid(row=1, column=10) # 恢复操作按钮 self.recover_button = Button(self.init_window_name, text="恢复", width='8', command=self.recover) self.recover_button.grid(row=0, column=15) # 标注撤销功能ctrl+z实现 self.back_button = Button(self.init_window_name, text="撤销", width='8', command=self.backToHistory) self.back_button.grid(row=0, column=16) self.result_data_Text.bind('<Control-Key-z>', self.backToHistory) self.result_data_Text.edit_separator() #功能函数 def str_trans_to_md5(self): src = self.init_data_Text.get(1.0, END).strip().replace("\n", "").encode() #print("src =",src) if src: try: myMd5 = hashlib.md5() myMd5.update(src) myMd5_Digest = myMd5.hexdigest() #print(myMd5_Digest) #输出到界面 self.result_data_Text.delete(1.0, END) self.result_data_Text.insert(1.0, myMd5_Digest) self.write_log_to_Text("INFO:str_trans_to_md5 success") except: self.result_data_Text.delete(1.0, END) self.result_data_Text.insert(1.0, "字符串转MD5失败") else: self.write_log_to_Text("ERROR:str_trans_to_md5 failed") #获取鼠标选中文本 def button_start(self, event): global s global line_no s = self.init_data_Text.index('@%s,%s' % (event.x, event.y)) line_no = str(s).split('.')[0] s = str(s).split('.')[1] def button_end(self, event): global e e = self.init_data_Text.index('@%s,%s' % (event.x, event.y)) e = str(e).split('.')[1] # 处理选中位置参数 def get_loc(self): print("get_loc", self.init_data_Text.selection_get(), self.init_data_Text.index('insert'), self.init_data_Text.index('insert').split('.')) e = int(str( self.init_data_Text.index('insert')).split('.')[1]) - 1 # 末尾列数 ll = int(str( self.init_data_Text.index('insert')).split('.')[0]) - 1 # 行号 con_num = len(self.init_data_Text.selection_get()) s = e - con_num + 1 # 开始列数 return s, e, ll def get_RMRB_res(self, text, string): # 注意:导入时需要将文字都进行多余字符删除。 # 存放数据集 print("t&string", string) sentences = [] # 临时存放每一个句子 sentence = [] content = text res_dict = {} # for line in open(label_filepath, encoding='UTF-8'): for line in string.split('\n'): # res = line.strip().split(' ') print("line", line) res = line.strip().split('\t') if res[0] == "": continue print("res: ", res) start = int(res[1]) end = int(res[2]) label = res[4] # label_id = label_dict.get(label) label_id = label distance = end - start + 1 for i in range(start, end + 1): #bioes if i == start and distance == 1: label_cate = 'S-' + label_id elif i == start and distance != 1: label_cate = 'B-' + label_id elif i == end: label_cate = 'I-' + label_id else: label_cate = 'I-' + label_id res_dict[i] = label_cate print("res_dict: ", res_dict) res_text = '' for indx, char in enumerate(content): if char == "。": sentences.append(sentence) sentence = [] elif char != " ": char_label = res_dict.get(indx, 'O') # f.write(char + '\t' + char_label + '\n') res_text += (char + '\t' + char_label + '\n') sentence.append([char, char_label]) else: continue return res_text #标记1 def show_jpbw(self): self.result_data_Text.edit_separator() start_index, end_index, ll = self.get_loc() print(self.init_data_Text.selection_get() + "\t" + str(self.btns_names[0]) + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[0]) + "\n") print(self.result_data_Text.get(END)) self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记2 def show_zzms(self, ): self.result_data_Text.edit_separator() start_index, end_index, ll = self.get_loc() print(self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[1]) + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[1]) + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记3 def show_dlzz(self): self.result_data_Text.edit_separator() start_index, end_index, ll = self.get_loc() print(self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + str(self.btns_names[2]) + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[2]) + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记4 def show_yw(self): self.result_data_Text.edit_separator() start_index, end_index, ll = self.get_loc() print(self.init_data_Text.selection_get() + "\t" + str(self.btns_names[3]) + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[3]) + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() # 标记5 def show_ss(self): self.result_data_Text.edit_separator() start_index, end_index, ll = self.get_loc() print(self.init_data_Text.selection_get() + "\t" + str(self.btns_names[4]) + "\n") self.result_data_Text.insert( END, self.init_data_Text.selection_get() + "\t" + str(start_index) + "\t" + str(end_index) + "\t" + str(ll) + "\t" + str(self.btns_names[4]) + "\n") self.max1 = self.result_data_Text.get('1.0', END) self.result_data_Text.edit_separator() #标注操作撤销功能 def callback(self, event): # 每当有字符插入的时候,就自动插入一个分割符,主要是防止每次撤销的时候会全部撤销 self.result_data_Text.edit_separator() def backToHistory(self): #撤销操作 if len(self.result_data_Text.get('1.0', 'end')) != 0: self.result_data_Text.edit_undo() else: #无字符时不能撤销 return def recover(self): #恢复操作 if len(self.max1) == len(self.result_data_Text.get('1.0', END)): return self.result_data_Text.edit_redo() #输入窗口一键清空功能 def delet_ofInput(self): self.init_data_Text.delete('1.0', 'end') #结果窗口一键清空功能 def delet_ofResult(self): self.result_data_Text.delete('1.0', 'end') def text_preprocess(self, text): text = text.replace('\n', '') return text #打开文件功能 def openfile(self): # 清空 self.init_data_Text.delete('1.0', 'end') fname = filedialog.askopenfilename(title='打开文件', filetypes=[('All Files', '*')]) # print() # self.filename=os.path.basename(fname) self.filePath, self.filename = os.path.split(fname) f = open(fname, 'r', encoding='utf-8', errors='ignore') f_content = ''.join(f.read()) self.content = f_content f_content = self.text_preprocess(f_content) print(self.content) self.init_data_Text.insert(END, f_content) #打开上一个文件功能 def openLastfile(self): # 清空 self.init_data_Text.delete('1.0', 'end') # this_dir_path = r'C:\Users\86137\Desktop\sequence_label-master\sequence_label-master\data\in' # 写死了,后续需要注意修改 this_dir_path = self.filePath # 写死了,后续需要注意修改 this_dir = list(os.walk(this_dir_path))[0][2] this_file = self.filename idx = this_dir.index(this_file) if idx + 1 > 1: last_file = this_dir_path + r'/' + this_dir[idx - 1] else: last_file = this_dir_path + r'/' + this_dir[0] print("last_file: ", last_file) self.filename = os.path.basename(last_file) f = open(last_file, 'r', encoding='utf-8', errors='ignore') # f_contet = ''.join(f.readlines()) f_contet = ''.join(f.read()) self.content = f_contet f_contet = self.text_preprocess(f_contet) self.init_data_Text.insert(END, f_contet) #打开下一个文件功能 def openNextfile(self): # 清空 self.init_data_Text.delete('1.0', 'end') # this_dir_path = r'C:\Users\86137\Desktop\sequence_label-master\sequence_label-master\data\in' # 写死了,后续需要注意修改 this_dir_path = self.filePath # 写死了,后续需要注意修改 this_dir = list(os.walk(this_dir_path))[0][2] this_file = self.filename idx = this_dir.index(this_file) print('idx: ', idx) if idx + 1 < len(this_dir): next_file = this_dir_path + r'/' + this_dir[idx + 1] else: next_file = this_dir_path + r'/' + this_dir[-1] print("next_file: ", next_file) self.filename = os.path.basename(next_file) f = open(next_file, 'r', encoding='utf-8', errors='ignore') f_contet = ''.join(f.read()) self.content = f_contet f_contet = self.text_preprocess(f_contet) self.init_data_Text.insert(END, f_contet) # 导出文件功能 def outputfile(self): if self.filename != "": # os.chdir(r'E:\GitTest\untitled\文本标注1.1\Annoation') # os.chdir(r'data/out') f = open("data/out/ann" + self.filename, 'w', encoding='utf-8', errors='ignore') print(self.result_data_Text.get("1.0", "end")) res_text = self.result_data_Text.get("1.0", "end") print("res_text", res_text) res_text = self.get_RMRB_res(self.content, res_text) print("res_text", res_text) f.write(res_text) json1 = json.dumps(self.result_data_Text.get("1.0", END)) print(json1) showinfo(title="成功", message="标注文件已导出至Annoation文件夹,文件名为" + self.filename) else: showinfo(title="错误", message="未找到指定文件") # 清空 self.result_data_Text.delete('1.0', 'end') #获取当前时间 def get_current_time(self): current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) return current_time #日志动态打印 def write_log_to_Text(self, logmsg): global LOG_LINE_NUM current_time = self.get_current_time() logmsg_in = str(current_time) + " " + str(logmsg) + "\n" #换行 if LOG_LINE_NUM <= 7: self.log_data_Text.insert(END, logmsg_in) LOG_LINE_NUM = LOG_LINE_NUM + 1 else: self.log_data_Text.delete(1.0, 2.0) self.log_data_Text.insert(END, logmsg_in)
class Application(tkinter.Tk): def __init__(self): """Initialize widgets, methods.""" tkinter.Tk.__init__(self) self.grid() fontoptions = families(self) font = Font(family="Verdana", size=10) menubar = tkinter.Menu(self) fileMenu = tkinter.Menu(menubar, tearoff=0) editMenu = tkinter.Menu(menubar, tearoff=0) fsubmenu = tkinter.Menu(editMenu, tearoff=0) ssubmenu = tkinter.Menu(editMenu, tearoff=0) # adds fonts to the font submenu and associates lambda functions for option in fontoptions: fsubmenu.add_command(label=option, command = lambda: font.configure(family=option)) # adds values to the size submenu and associates lambda functions for value in range(1,31): ssubmenu.add_command(label=str(value), command = lambda: font.configure(size=value)) # adds commands to the menus menubar.add_cascade(label="File",underline=0, menu=fileMenu) menubar.add_cascade(label="Edit",underline=0, menu=editMenu) fileMenu.add_command(label="New", underline=1, command=self.new, accelerator="Ctrl+N") fileMenu.add_command(label="Open", command=self.open, accelerator="Ctrl+O") fileMenu.add_command(label="Save", command=self.save, accelerator="Ctrl+S") fileMenu.add_command(label="Exit", underline=1, command=exit, accelerator="Ctrl+Q") editMenu.add_command(label="Copy", command=self.copy, accelerator="Ctrl+C") editMenu.add_command(label="Cut", command=self.cut, accelerator="Ctrl+X") editMenu.add_command(label="Paste", command=self.paste, accelerator="Ctrl+V") editMenu.add_cascade(label="Font", underline=0, menu=fsubmenu) editMenu.add_cascade(label="Size", underline=0, menu=ssubmenu) editMenu.add_command(label="Color", command=self.color) editMenu.add_command(label="Bold", command=self.bold, accelerator="Ctrl+B") editMenu.add_command(label="Italic", command=self.italic, accelerator="Ctrl+I") editMenu.add_command(label="Underline", command=self.underline, accelerator="Ctrl+U") editMenu.add_command(label="Overstrike", command=self.overstrike, accelerator="Ctrl+T") editMenu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z") editMenu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y") self.config(menu=menubar) """Accelerator bindings. The cut, copy, and paste functions are not bound to keyboard shortcuts because Windows already binds them, so if Tkinter bound them as well whenever you typed ctrl+v the text would be pasted twice.""" self.bind_all("<Control-n>", self.new) self.bind_all("<Control-o>", self.open) self.bind_all("<Control-s>", self.save) self.bind_all("<Control-q>", self.exit) self.bind_all("<Control-b>", self.bold) self.bind_all("<Control-i>", self.italic) self.bind_all("<Control-u>", self.underline) self.bind_all("<Control-T>", self.overstrike) self.bind_all("<Control-z>", self.undo) self.bind_all("<Control-y>", self.redo) self.text = ScrolledText(self, state='normal', height=30, wrap='word', font = font, pady=2, padx=3, undo=True) self.text.grid(column=0, row=0, sticky='NSEW') # Frame configuration self.grid_columnconfigure(0, weight=1) self.resizable(True, True) """Command functions. *args is included because the keyboard bindings pass two arguments to the functions, while clicking in the menu passes only 1.""" def new(self, *args): """Creates a new window.""" app = Application() app.title('Python Text Editor') app.option_add('*tearOff', False) app.mainloop() def color(self): """Changes selected text color.""" try: (rgb, hx) = tkinter.colorchooser.askcolor() self.text.tag_add('color', 'sel.first', 'sel.last') self.text.tag_configure('color', foreground=hx) except TclError: pass def bold(self, *args): """Toggles bold for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "bold" in current_tags: self.text.tag_remove("bold", "sel.first", "sel.last") else: self.text.tag_add("bold", "sel.first", "sel.last") bold_font = Font(self.text, self.text.cget("font")) bold_font.configure(weight="bold") self.text.tag_configure("bold", font=bold_font) except TclError: pass def italic(self, *args): """Toggles italic for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "italic" in current_tags: self.text.tag_remove("italic", "sel.first", "sel.last") else: self.text.tag_add("italic", "sel.first", "sel.last") italic_font = Font(self.text, self.text.cget("font")) italic_font.configure(slant="italic") self.text.tag_configure("italic", font=italic_font) except TclError: pass def underline(self, *args): """Toggles underline for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "underline" in current_tags: self.text.tag_remove("underline", "sel.first", "sel.last") else: self.text.tag_add("underline", "sel.first", "sel.last") underline_font = Font(self.text, self.text.cget("font")) underline_font.configure(underline=1) self.text.tag_configure("underline", font=underline_font) except TclError: pass def overstrike(self, *args): """Toggles overstrike for selected text.""" try: current_tags = self.text.tag_names("sel.first") if "overstrike" in current_tags: self.text.tag_remove("overstrike", "sel.first", "sel.last") else: self.text.tag_add("overstrike", "sel.first", "sel.last") overstrike_font = Font(self.text, self.text.cget("font")) overstrike_font.configure(overstrike=1) self.text.tag_configure("overstrike", font=overstrike_font) except TclError: pass def undo(self, *args): """Undo function""" try: self.text.edit_undo() except TclError: pass def redo(self, *args): """Redo function""" try: self.text.edit_redo() except TclError: pass def copy(self, *args): """Copy text""" self.clipboard_clear() self.clipboard_append(self.text.selection_get()) def cut(self, *args): """Cut text""" self.copy self.text.delete("sel.first", "sel.last") def paste(self, *args): """Paste text""" insertion = self.selection_get(selection = "CLIPBOARD") self.text.insert(0.0, insertion) def open(self, *args): """Opens a file dialog to open a plain text file.""" filename = tkinter.filedialog.askopenfilename() with open(filename) as f: text = f.read() self.text.delete("1.0", "end") self.text.insert('insert', text) def save(self, *args): try: """Opens a file dialog to save the text in plain text format.""" text = self.text.get("1.0", "end") filename = tkinter.filedialog.asksaveasfilename() with open(filename, 'w') as f: f.write(text) except FileNotFoundError: pass def exit(self, *args): """Exits the program.""" self.quit()