class TextEditor(): # see PyEdit for more def __init__(self, parent=None): # TODO: 1226 why This can generate independent window ? #frm=Toplevel(Frame.__init__(self, parent)) frm=Toplevel() # TODO : assign title based on cmdline tag frm.title('New Text') # TODO , how to make button and Text in a better Layout format ? # grid() param to learn Button(frm, text='Save', command=self.onSave).grid(row=0,column=0) Button(frm, text='Cut', command=self.onCut).grid(row=0,column=1) Button(frm, text='Paste', command=self.onPaste).grid(row=0,column=2) Button(frm, text='Find', command=self.onFind).grid(row=0,column=3) self.text = ScrolledText(frm) self.text.grid(row=1,columnspan=4) #Button(self, text='Save', command=self.onSave).grid() #Button(self, text='Cut', command=self.onCut).grid() #Button(self, text='Paste', command=self.onPaste).grid() #Button(self, text='Find', command=self.onFind).grid() #self.text = ScrolledText(self) def gettext(self): # returns a string return self.text.get('1.0', END+'-1c') # first through last def onSave(self): filename = asksaveasfilename() #print(filename) if filename: alltext = self.gettext() # first through last open(filename, 'w').write(alltext) # store text in file def onCut(self): text = self.text.get(SEL_FIRST, SEL_LAST) # error if no select self.text.delete(SEL_FIRST, SEL_LAST) # should wrap in try self.text.clipboard_clear() self.text.clipboard_append(text) def onPaste(self): # add clipboard text try: text = self.text.selection_get(selection='CLIPBOARD') self.text.insert(INSERT, text) except TclError: pass # not to be pasted def onFind(self): target = askstring('SimpleEditor', 'Search String?') if target: where = self.text.search(target, INSERT, END) # from insert cursor if where: # returns an index print(where) pastit = where + ('+%dc' % len(target)) # index past target #self.text.tag_remove(SEL, '1.0', END) # remove selection self.text.tag_add(SEL, where, pastit) # select found target self.text.mark_set(INSERT, pastit) # set insert mark self.text.see(INSERT) # scroll display self.text.focus() # select text widget
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 Window(): def __init__(self, title, height, width, bg_color, resizable=(False, False)): self.root = tk.Tk() #build te main root #make it more beautiful self.root.title(title) self.root.geometry(f"{width}x{height}+350+150") self.root.config(bg=bg_color) self.root.resizable = (resizable[0], resizable[1]) self.save_auto = tk.BooleanVar() #program it while the buttom is clicked self.root.bind_all("<Control-s>", self.save) self.root.bind_all("<Control-w>", self.make_work) self.root.bind_all("<Control-d>", self.save_as) self.root.bind_all("<Control-n>", self.new) self.root.bind_all("<Control-m>", self.new_win) self.root.bind_all("<Control-o>", self.open) self.root.focus_set() self.root.grab_set() #function of closing window self.root.protocol("WM_DELETE_WINDOW", lambda: self.close_window("root")) #initialization of all objects that i'm gonna use self.default_font = 11 self.word_wrap_choice = tk.BooleanVar(value=True) def run(self): #run function self.draw_menu() self.draw_scrolled_text() self.root.mainloop() def close_window(self, word): #function that apears when we close_window #and asks as wanna we sawe material or not if word == "root": if len(self.st.get("0.0", "1.1")) == 0 or self.name is not None: self.root.destroy() else: choice = messagebox.askyesnocancel( ' action Box', 'Do you wanna save your changes??') if choice is True: self.save_as() elif choice is False: self.root.destroy() elif choice is None: pass return self.st elif word == "win": if len(self.win_st.get("0.0", "1.1")) == 0 or self.name is not None: self.win.destroy() else: choice = messagebox.askyesnocancel( ' action Box', 'Do you wanna save your changes??') if choice: self.save_as() elif choice is False: self.win.destroy() elif choice is None: pass return self.win_st def make_work(self, *args, **kwargs): #function that gets the selected text and #uses another function to aneble our labels ('cut', 'copy', 'paste') self.get_selected = self.st.get(tk.SEL_FIRST, tk.SEL_LAST) self.work_with_selected_text("root") return self.get_selected def make_work_new_win(self, *args, **kwargs): #the sae one as the previoys but it works with new window self.get_selected = self.win_st.get(tk.SEL_FIRST, tk.SEL_LAST) self.work_with_selected_text("win") return self.get_selected #function that open the folders and save our information #can use just clicking 'Ctrl+d' def save_as(self, *args, **kwargs): try: #open main terminal to save our results self.name = fd.asksaveasfilename(filetypes=(("Text file", "*.txt"), ("Python files", "*.py"))) #when we chosed file if opens it with open(self.name, "w") as f: f.write( self.st.get("0.0", tk.END) ) # and write there information that there is in this file except FileNotFoundError: pass return self.name #function that save our information but nou open folders when it was used already #can use just clicking 'Ctrl+s' def save(self, *args, **kwargs): try: if self.name is None: #open main terminal to save our results self.name = fd.asksaveasfilename(filetypes=(("Text file", "*.txt"), ("Python files", "*.py"))) #when we chosed file if opens it with open(self.name, "w") as f: f.write( self.st.get("0.0", tk.END) ) # write there information that there is in this file except FileNotFoundError: pass return self.name #open folders to open file that we're looking for def open(self, name_type, *args, **kwargs): name = fd.askopenfilename() if name_type == "root": #main operation if name: with open(name, "r") as f: #open main teminal self.st.delete("0.0", tk.END) self.st.insert( tk.END, f.read()) #insert the text that we have chosen elif name_type == "win": # the same but only for new_win if name: with open(name, "r") as f: self.win_st.delete("0.0", tk.END) self.win_st.insert(tk.END, f.read()) def work_with_selected_text( self, name_type): #function that nake our labelf feel NORMAL if name_type == "root": if len(self.get_selected ) != 0: #if len of selected text is not zero self.new_menu2.entryconfig( 0, state=tk.NORMAL) #anebling our labels self.new_menu2.entryconfig(1, state=tk.NORMAL) self.new_menu2.entryconfig(2, state=tk.NORMAL) self.new_menu2.entryconfig(3, state=tk.NORMAL) self.new_menu2.entryconfig(4, state=tk.NORMAL) elif name_type == "win": if len(self.get_selected ) != 0: #if len of selected text is not zero self.new_menu_new_win.entryconfig( 0, state=tk.NORMAL) #anebling our labels self.new_menu_new_win.entryconfig(1, state=tk.NORMAL) self.new_menu_new_win.entryconfig(2, state=tk.NORMAL) self.new_menu_new_win.entryconfig(3, state=tk.NORMAL) #main function that creates new window in our Noetepad def new_win(self, *args, **kwargs): #asks if we wanna save our changes choice = messagebox.askyesnocancel('Yes or No or Cancel action Box', 'Do you wanna save your changes??') if choice is False: #if answer is No self.win = tk.Toplevel(self.root) #we create new win #make it looks a bit attractive self.win.title("Untitled") self.win.geometry(f"{900}x{520}+500+150") self.win.config(bg="white") #creating scrollText to meke it like a real Notepadd self.win_st = ScrolledText(self.win, selectforeground="white", fg="black", font=("Consolas", 11, "bold"), wrap="word", width=200, height=100) self.win_st.pack() #pack it in our screen #create a status bur into our screen menu_bar = tk.Menu(self.win) self.win.bind_all("<Control-w>", self.make_work_new_win ) #to uneble our ('cut','copy','paste') labels #creating adition little-memu on our status bar new_menu = tk.Menu(menu_bar, tearoff=0) self.new_menu_new_win = tk.Menu( menu_bar, tearoff=0 ) #we created it as self_object because we're gonna use into #out of this function new_Format = tk.Menu(menu_bar, tearoff=0) new_font = tk.Menu(menu_bar, tearoff=0) new_view = tk.Menu(menu_bar, tearoff=0) new_zoom = tk.Menu(menu_bar, tearoff=0) new_help = tk.Menu(menu_bar, tearoff=0) #add kabels on the each little-menu new_menu.add_command(label="New Ctrl+N", ) new_menu.add_command(label="New Window Ctrl+M", command=self.new_win) new_menu.add_command( label="Open Ctrl+O", command=lambda: self.open("win")) #add function new_menu.add_separator() #add separator for this little-menu new_menu.add_command(label="Save Ctrl + s") new_menu.add_cascade(label="Save as Ctrl + d") new_menu.add_separator() new_menu.add_command(label="exit", command=lambda: self.close_window("win")) #adding special labels self.new_menu_new_win.add_command( label="Cut", command=lambda: self.get_cut("win")) self.new_menu_new_win.add_command( label="Copy", command=lambda: self.get_copy("win")) self.new_menu_new_win.add_command( label="Paste", command=lambda: self.get_paste("win")) self.new_menu_new_win.add_command( label="Delete", command=lambda: self.get_delete("win")) self.new_menu_new_win.add_separator() self.new_menu_new_win.add_command( label="Select All", command=lambda: self.get_select_text("win")) self.new_menu_new_win.add_command( label="Time/Data", command=lambda: self.get_current_time("win")) self.new_menu_new_win.entryconfig( 0, state=tk.DISABLED) #make all of this labels disabled self.new_menu_new_win.entryconfig( 1, state=tk.DISABLED) #make all of this labels disabled self.new_menu_new_win.entryconfig( 2, state=tk.DISABLED) #make all of this labels disabled self.new_menu_new_win.entryconfig( 3, state=tk.DISABLED) #make all of this labels disabled #add checkbutton list of fonts if we wanna change this one new_Format.add_checkbutton(label="Word wrap", variable=self.word_wrap_choice, onvalue=True, offvalue=False, command=self.word_wrap_funk) new_font.add_command( label="Arial", command=lambda: self.make_font("Arial", "win")) new_font.add_command( label="Consolas", command=lambda: self.make_font("Consolas", "win")) new_font.add_command( label="Calibri", command=lambda: self.make_font("Calibri", "win")) new_font.add_command( label="Modern", command=lambda: self.make_font("Modern", "win")) #add zoom labels with commands new_zoom.add_command( label="Zoom in", command=lambda: self.zoom_in_command("zoom in", "win")) new_zoom.add_command( label="Zoom out", command=lambda: self.zoom_in_command("zoom out", "win")) new_zoom.add_command( label="Restore to default settings", command=lambda: self.zoom_in_command("default", "win")) #add this all little-menu to our main menu menu_bar.add_cascade(label="File", menu=new_menu) menu_bar.add_cascade(label="Edit", menu=self.new_menu_new_win) menu_bar.add_cascade(label="Format", menu=new_Format) new_Format.add_cascade(label="Font...", menu=new_font) menu_bar.add_cascade(label="View", menu=new_view) menu_bar.add_cascade(label="Help", menu=new_help) new_view.add_cascade(label="Zoom", menu=new_zoom) self.win.configure(menu=menu_bar) #add our main menu to main root elif choice is True: #in choice is true save_as (wanna save our changes) self.save_as() elif choice is None: #if choice is None, means we cliked on 'Cancel' pass #dont do anything self.win.protocol( "WM_DELETE_WINDOW", lambda: self.close_window("win")) #funk closing new_window return self.win_st, self.win, self.new_menu_new_win #return all elements we will use later def new(self, *args, **kwargs): #new_funk just clean the whole field self.st.delete("0.0", tk.END) def draw_scrolled_text( self): #funk that draw scrolled text on our main root self.st = ScrolledText(self.root, selectforeground="white", fg="black", font=("Consolas", 11, "bold"), width=200, height=100) #all the parameters self.st.pack() return self.st def word_wrap_funk( self): #if we wanna end our line with word we use this funk if self.word_wrap_choice: #checkbuttom that has two types ("true", "false") self.st.configure( wrap="word") #if true we change configuration of dcrilled text def make_font(self, chosenfont, place): #change size of our font if place == "root": #on main root self.st.configure(font=(chosenfont, 11)) elif place == "win": #on new window self.win_st.configure(font=(chosenfont, 11)) def zoom_in_command(self, type_size, place): #funk zooms out font #for main root if type_size == "zoom in" and place == "root": #if zoom_in font getting bigger self.default_font += 2 self.st.configure(font=("Arial", self.default_font)) elif type_size == "zoom out" and place == "root": #if zoom_our font getting smaller self.default_font -= 2 self.st.configure(font=("Arial", self.default_font)) elif type_size == "default" and place == "root": #if default returns start font size self.st.configure(font=("Arial", 11)) #for new window elif type_size == "zoom in" and place == "win": #if zoom_in font getting bigger self.default_font += 2 self.win_st.configure(font=("Arial", self.default_font)) elif type_size == "zoom out" and place == "win": #if zoom_our font getting smaller self.default_font -= 2 self.win_st.configure(font=("Arial", self.default_font)) elif type_size == "default" and place == "win": #if default returns start font size self.win_st.configure(font=("Arial", 11)) return self.default_font def get_cut(self, name_type): #funk that cut selected text if name_type == "root": #for root try: self.storage_for_copy_cut_paste = self.st.get( tk.SEL_FIRST, tk.SEL_LAST) #get selected text self.st.delete("sel.first", "sel.last") #delete selected except Exception: pass return self.storage_for_copy_cut_paste elif name_type == "win": #for new window try: self.storage_for_copy_cut_paste = self.win_st.get( tk.SEL_FIRST, tk.SEL_LAST) #get selected text self.win_st.delete("sel.first", "sel.last") #delete selected except Exception: pass return self.storage_for_copy_cut_paste def get_copy(self, name_type): #funk that copy selected text if name_type == "root": #for root try: self.st.clipboard_clear() self.storage_for_copy_cut_paste = self.st.get( tk.SEL_FIRST, tk.SEL_LAST) #get selected text text = self.storage_for_copy_cut_paste self.st.clipboard_append(text) except Exception: pass return self.storage_for_copy_cut_paste elif name_type == "win": #for new window try: self.win_st.clipboard_clear() self.storage_for_copy_cut_paste = self.win_st.get( tk.SEL_FIRST, tk.SEL_LAST) #get selected text text = self.storage_for_copy_cut_paste self.win_st.clipboard_append(text) except Exception: pass return self.storage_for_copy_cut_paste def get_paste(self, name_type): #funk that paste selected text if name_type == "root": #for root try: text = self.storage_for_copy_cut_paste #get text that has already been set self.st.insert('insert', text) #add it to scrolled text except Exception: pass return self.storage_for_copy_cut_paste elif name_type == "win": #for root try: text = self.storage_for_copy_cut_paste #get text that has already been set self.win_st.insert('insert', text) #add it to scrolled text except Exception: pass return self.storage_for_copy_cut_paste def get_delete(self, name_type): #delete whole selected text if name_type == "root": #for root try: self.st.delete("sel.first", "sel.last") except Exception: pass elif name_type == "win": #for new win try: self.win_st.delete("sel.first", "sel.last") except Exception: pass def about_notepad_command(self): #func thet creates new field to see the #information of this notepad new_win = tk.Toplevel(self.root, width=500, height=500) new_win.geometry("500x400+500+200") new_win.title("About") new_st = ScrolledText(new_win) new_st.insert(tk.END, text) new_st.pack() def get_select_text(self, name_type): if name_type == "root": self.st.tag_add("sel", "1.0", "end") #get selected from root elif name_type == "win": self.win_st.tag_add("sel", "1.0", "end") #get selected from new win def find_word(self): self.win_new = tk.Toplevel(self.root) tk.Label(self.win_new, text="What ti find").grid(row=0, column=0) self.what_to_find = tk.Entry(self.win_new) self.what_to_find.grid(row=0, column=1, columnspan=3) button = tk.Button(self.win_new, text="Find", command=self.find_word_main) button.grid(row=1, column=1) return self.what_to_find, self.new_win def find_word_main(self): position_of_word = self.st.get("0.0", "end").find(self.what_to_find.get()) pos = 1 while position_of_word > len(self.st.get(f"{pos}.0", f"{pos}.100")): position_of_word -= len(self.st.get(f"{pos}.0", f"{pos}.100")) pos += 1 else: position_of_word = self.st.get(f"{pos}.0", "end").find(self.what_to_find.get()) self.st.tag_add( "sel", f"{pos}.{position_of_word}", f"{pos}.{position_of_word + len(self.what_to_find.get())}") self.win_new.destroy() def get_current_time(self, name_type): #show current time d = datetime.today() if name_type == "root": self.st.insert("end", d.strftime("%d-%B-%Y %H:%M:%S")) elif name_type == "win": self.win_st.insert("end", d.strftime("%d-%B-%Y %H:%M:%S")) def new_delete_whole_text(self): #delete everything self.st.delete("1.0", "end") def draw_menu(self): #creating tme main menu on root menu_bar = tk.Menu(self.root) #main menu #creating little menues new_menu = tk.Menu(menu_bar, tearoff=0) self.new_menu2 = tk.Menu( menu_bar, tearoff=0) #we use iy out of this function to make #label in there state Normal new_Format = tk.Menu(menu_bar, tearoff=0) new_font = tk.Menu(menu_bar, tearoff=0) new_view = tk.Menu(menu_bar, tearoff=0) new_zoom = tk.Menu(menu_bar, tearoff=0) new_help = tk.Menu(menu_bar, tearoff=0) #adding label and their command to each little menu bar new_menu.add_command(label="New Ctrl+N", command=self.new_delete_whole_text) new_menu.add_command(label="New Window Ctrl+M", command=self.new_win) new_menu.add_command(label="Open Ctrl+O", command=lambda: self.open("root")) new_menu.add_separator() # add separator new_menu.add_command(label="Save Ctrl + s", command=self.save) new_menu.add_cascade(label="Save as Ctrl + d", command=self.save_as) new_menu.add_separator() new_menu.add_command(label="exit", command=lambda: self.close_window("root")) self.new_menu2.add_command(label="Cut", command=lambda: self.get_cut("root")) self.new_menu2.add_command(label="Copy", command=lambda: self.get_copy("root")) self.new_menu2.add_command(label="Paste", command=lambda: self.get_paste("root")) self.new_menu2.add_command(label="Delete", command=lambda: self.get_delete("root")) self.new_menu2.add_command(label="Find", command=self.find_word) self.new_menu2.add_separator() self.new_menu2.add_command( label="Select All", command=lambda: self.get_select_text("root")) self.new_menu2.add_command( label="Time/Data", command=lambda: self.get_current_time("root")) #making labels disabled self.new_menu2.entryconfig(0, state=tk.DISABLED) self.new_menu2.entryconfig(1, state=tk.DISABLED) self.new_menu2.entryconfig(2, state=tk.DISABLED) self.new_menu2.entryconfig(3, state=tk.DISABLED) self.new_menu2.entryconfig(4, state=tk.DISABLED) #add checkbutton to wrap funk new_Format.add_checkbutton(label="Word wrap", variable=self.word_wrap_choice, onvalue=True, offvalue=False, command=self.word_wrap_funk) # for canging our font new_font.add_command(label="Arial", command=lambda: self.make_font("Arial", "root")) new_font.add_command( label="Consolas", command=lambda: self.make_font("Consolas", "root")) new_font.add_command(label="Calibri", command=lambda: self.make_font("Calibri", "root")) new_font.add_command(label="Modern", command=lambda: self.make_font("Modern", "root")) #zoom funk new_zoom.add_command( label="Zoom in", command=lambda: self.zoom_in_command("zoom in", "root")) new_zoom.add_command( label="Zoom out", command=lambda: self.zoom_in_command("zoom out", "root")) new_zoom.add_command( label="Restore to default settings", command=lambda: self.zoom_in_command("default", "root")) new_help.add_command(label="About Notepad", command=self.about_notepad_command) #add little menus to main menu_bar menu_bar.add_cascade(label="File", menu=new_menu) menu_bar.add_cascade(label="Edit", menu=self.new_menu2) menu_bar.add_cascade(label="Format", menu=new_Format) new_Format.add_cascade(label="Font...", menu=new_font) menu_bar.add_cascade(label="View", menu=new_view) new_view.add_cascade(label="Zoom", menu=new_zoom) menu_bar.add_cascade(label="Help", menu=new_help) #add main menu to root self.root.configure(menu=menu_bar) return self.new_menu2
class Google_translator: def __init__(self, root): self.root = root self.root.title('Google Translator') self.root.geometry('280x460') self.root.config(bg="#4285F4") self.google_logo = PhotoImage(file='img\\logo.png') self.mic_img = PhotoImage(file="img\\microphone.png") self.speaker_img = PhotoImage(file="img\\speaker (1).png") self.input_text = ScrolledText(self.root, width=30, height=7) self.input_text.place(x=10, y=10) self.choose_langauge = ttk.Combobox(self.root, state='readonly', font=('arial', 10), width=34) self.choose_langauge['values'] = ( 'Afrikaans', 'Albanian', 'Arabic', 'Armenian', ' Azerbaijani', 'Basque', 'Belarusian', 'Bengali', 'Bosnian', 'Bulgarian', ' Catalan', 'Cebuano', 'Chichewa', 'Chinese', 'Corsican', 'Croatian', ' Czech', 'Danish', 'Dutch', 'English', 'Esperanto', 'Estonian', 'Filipino', 'Finnish', 'French', 'Frisian', 'Galician', 'Georgian', 'German', 'Greek', 'Gujarati', 'Haitian Creole', 'Hausa', 'Hawaiian', 'Hebrew', 'Hindi', 'Hmong', 'Hungarian', 'Icelandic', 'Igbo', 'Indonesian', 'Irish', 'Italian', 'Japanese', 'Javanese', 'Kannada', 'Kazakh', 'Khmer', 'Kinyarwanda', 'Korean', 'Kurdish', 'Kyrgyz', 'Lao', 'Latin', 'Latvian', 'Lithuanian', 'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Mongolian', 'Myanmar', 'Nepali', 'Norwegian' 'Odia', 'Pashto', 'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Romanian', 'Russian', 'Samoan', 'Scots Gaelic', 'Serbian', 'Sesotho', 'Shona', 'Sindhi', 'Sinhala', 'Slovak', 'Slovenian', 'Somali', 'Spanish', 'Sundanese', 'Swahili', 'Swedish', 'Tajik', 'Tamil', 'Tatar', 'Telugu', 'Thai', 'Turkish', 'Turkmen', 'Ukrainian', 'Urdu', 'Uyghur', 'Uzbek', 'Vietnamese', 'Welsh', 'Xhosa', 'Yiddish', 'Yoruba', 'Zulu', ) self.choose_langauge.place(x=10, y=140) self.choose_langauge.current(0) self.output_text = ScrolledText(self.root, width=30, height=10) self.output_text.place(x=10, y=175) button = Button(self.root, text="Translate", cursor="hand2", width=10, command=self.translate) button.place(x=190, y=350) copy_button = Button(self.root, text="Copy Text", cursor="hand2", width=10, command=self.copy_text) copy_button.place(x=100, y=350) clear = Button(self.root, text="Clear", cursor="hand2", width=10, command=self.clear) clear.place(x=10, y=350) Button(self.root, image=self.mic_img, bd=0, bg="white", command=self.listen).place(x=220, y=90) Button(self.root, image=self.speaker_img, bd=0, bg="white", command=self.speak).place(x=220, y=303) Label(root, image=self.google_logo).place(x=10, y=390) Label(root, text="Google", font=('arial black', 30), bg="#4285F4", fg="white").place(x=100, y=385) def translate(self): language_1 = self.input_text.get(1.0, END) cl = self.choose_langauge.get() if language_1 == '': messagebox.showerror('Google Translator', 'please fill the box') else: translator = Translator() output = translator.translate(language_1, dest=cl) self.output_text.delete(1.0, END) self.output_text.insert('end', output.text) def clear(self): self.input_text.delete(1.0, 'end') self.output_text.delete(1.0, 'end') def copy_text(self): self.output_text.clipboard_clear() self.output_text.clipboard_append(self.output_text.get(1.0, END)) def speak(self): tts = gTTS(text=self.output_text.get(1.0, END), lang="en") r = random.randint(0, 100000) audio_file = "audio-"+str(r)+".mp3" tts.save(audio_file) playsound.playsound(audio_file) os.remove(audio_file) def listen(self): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) string = "" string = r.recognize_google(audio) self.input_text.delete("1.0", END) self.input_text.insert(END, string)
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)