class GuiConsole(Frame): def __init__(self, master=None, cnf={}, **kw): super(GuiConsole, self).__init__(master, cnf, **kw) self.pack(fill=BOTH, expand=YES) self.console = ScrolledText(self, font=('Source Code Pro', 12, 'normal')) self.console.pack(side=TOP, fill=BOTH, expand=YES, padx=5, pady=5) self.console.focus() self.console.mark_set(INSERT, '1.0') def clear(self): self.console.delete('1.0', END) def write(self, text): text = '{}'.format(text) self.console.insert(INSERT, text) self.console.mark_set(INSERT, INSERT+'+{}c'.format(len(text))) def writeline(self, text): self.write('{}\n'.format(text)) def writelines(self, lines): for line in lines: self.writeline(line) def read(self): pass
def main(): window = Tk() window.title("TeamChooser") window.geometry('600x800') lbl = Label(window, text="Players: (name, score)") lbl.grid(column=0, row=0) txt = ScrolledText(window, width=25) txt.grid(column=0, row=1, pady=10, padx=10) txt.focus() lbl2 = Label(window, text="Seperations:") lbl2.grid(column=0, row=2) txt2 = ScrolledText(window, width=25, height=10) txt2.grid(column=0, row=3, pady=10, padx=10) lbl3 = Label(window, text="Results") lbl3.grid(column=1, row=0) txt3 = ScrolledText(window, width=25) txt3.grid(column=1, row=1, pady=10, padx=10) btn = Button(window, text="Run Algorithm", command=lambda: calc_teams(txt.get(1.0, "end"), txt2.get(1.0, "end"), txt3)) btn.grid(column=0, row=4) window.mainloop()
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 EditMemory(Dialog): def __init__(self, parent, memory, state): self.memory = memory self.state = state self.inheritability = tk.StringVar() self.delete_button = None self.memory_textbox = None Dialog.__init__(self, parent, title="Edit memory entry", enter_to_apply=False) def body(self, master): self.memory_textbox = ScrolledText(master, height=3) self.memory_textbox.grid(row=master.grid_size()[1], column=0, columnspan=2) self.memory_textbox.configure( font=Font( family="Georgia", size=12), # Other nice options: Helvetica, Arial, Georgia spacing1=10, foreground=text_color(), background=bg_color(), padx=3, pady=3, spacing2=3, # Spacing between lines spacing3=5, wrap="word", ) self.memory_textbox.insert(tk.INSERT, self.memory['text']) self.memory_textbox.focus() row = master.grid_size()[1] create_side_label(master, "Inheritability", row) inheritability_options = ('none', 'subtree', 'delayed') self.inheritability.set(self.memory['inheritability']) dropdown = tk.OptionMenu(master, self.inheritability, *inheritability_options) dropdown.grid(row=row, column=1, pady=3) self.delete_button = create_button(master, "Delete memory", self.delete_memory, width=15) def delete_memory(self): self.state.delete_memory_entry(self.memory) self.cancel() def apply(self): memory_text = self.memory_textbox.get("1.0", 'end-1c') self.memory['text'] = memory_text self.memory['inheritability'] = self.inheritability.get()
class CreateMemory(Dialog): def __init__(self, parent, node, state, default_inheritability='delayed'): self.node = node self.state = state self.inheritability = tk.StringVar() self.default_inheritability = default_inheritability self.memory_textbox = None Dialog.__init__(self, parent, title="Add memory entry", enter_to_apply=False) def body(self, master): self.memory_textbox = ScrolledText(master, height=3) self.memory_textbox.grid(row=master.grid_size()[1], column=0, columnspan=2) self.memory_textbox.configure( font=Font( family="Georgia", size=12), # Other nice options: Helvetica, Arial, Georgia spacing1=10, foreground=text_color(), background=bg_color(), padx=3, pady=3, spacing2=3, # Spacing between lines spacing3=5, wrap="word", ) self.memory_textbox.focus() row = master.grid_size()[1] create_side_label(master, "Inheritability", row) inheritability_options = ('none', 'subtree', 'delayed') self.inheritability.set(self.default_inheritability) dropdown = tk.OptionMenu(master, self.inheritability, *inheritability_options) dropdown.grid(row=row, column=1, pady=3) def apply(self): memory_text = self.memory_textbox.get("1.0", 'end-1c') if memory_text: self.state.create_memory_entry(self.node, memory_text, self.inheritability.get())
class Type: def __init__(self, master, essay, tips): self.master = master self.essay = essay shuffle(tips) self.tips = iter(cycle(tips)) self.temp = self.essay[1] self.passage = Label(self.master, text=self.essay[0], padx=45, pady=50, bg='#ffffbb', font=('Verdana', 15), relief=RAISED, justify=LEFT, wraplength=1269) self.passage.pack(side=TOP, fill=X) self.textinput = ScrolledText(self.master, width=90, height=18, bd=10, font=('Garamond', 15), state=NORMAL, wrap=WORD) self.textinput.place(x=290, y=290) self.timer_clicked = False minutes = self.temp // 60 seconds = self.temp % 60 self.countdown = Label(text='{}:{:02d}'.format(minutes, (seconds)), font=('Arial', 19), bg='yellow', relief=GROOVE) self.countdown.place(x=620, y=250) self.countdown.bind('<Button-1>', self.count) self.textinput.bind('<Control-Return>', lambda dummy=0: self.submit()) self.submitted = False self.draw() def draw(self): self.result = Label(text='', font=('Arial', 18, 'bold')) self.result.place(x=50, y=350) self.remark = Label(text='', font=('Arial', 18, 'bold')) self.remark.place(x=65, y=550) self.random_tip = Button(self.master, text='Tips', font=('Arial', 12, 'bold'), fg='black', bg='powder blue', relief=GROOVE, width=10, command=self.show_tips) self.random_tip.place(x=1180, y=370) self.exit_btn = Button(self.master, text='Quit', font=('Arial', 12, 'bold'), fg='black', bg='powder blue', relief=GROOVE, width=10, command=lambda: self.master.destroy()) self.exit_btn.place(x=1180, y=420) self.restart_btn = Button(self.master, text='Restart', font=('Arial', 12, 'bold'), fg='black', bg='powder blue', width=10, relief=GROOVE, command=self.restart) self.restart_btn.place(x=1180, y=550) level = ['Easy', 'Normal', 'Hard'] self.level_var = StringVar() self.level_var.set('Normal') self.difficulty_easy = ttk.Radiobutton(self.master, text='Easy', variable=self.level_var, value='Easy', command=self.level_change) self.difficulty_easy.place(x=1280, y=280) self.difficulty_normal = ttk.Radiobutton(self.master, text='Normal', variable=self.level_var, value='Normal', command=self.level_change) self.difficulty_normal.place(x=1280, y=300) self.difficulty_hard = ttk.Radiobutton(self.master, text='Hard', variable=self.level_var, value='Hard', command=self.level_change) self.difficulty_hard.place(x=1280, y=320) self.difficulty = Label(self.master, text=f'Difficulty: Normal', font=('Times', 14), fg='orange') self.difficulty.place(x=1190, y=230) self.start_text = Label(self.master, text='Click the Timer to Start!', font=('Courier', 13, 'bold underline')) self.start_text.place(x=530, y=220) def submit(self): self.submitted = True def calculate(self): total = self.essay[0].split() typed_words = self.textinput.get(1.0, END).split() correct = [] incorrect = [] wrong_case = [] excess_words = [] if len(typed_words) == len(total): for i in range(len(total)): if total[i] == typed_words[i]: correct.append(total[i]) else: incorrect.append(typed_words[i]) if typed_words[i].lower() == total[i].lower(): wrong_case.append(typed_words[i]) elif len(typed_words) < len(total): diff = len(total) - len(typed_words) for i in range(len(typed_words)): if typed_words[i] == total[i]: correct.append(typed_words[i]) else: incorrect.append(typed_words[i]) if typed_words[i].lower() == total[i].lower(): wrong_case.append(typed_words[i]) empty = ['space'] * diff for e in empty: incorrect.append(e) else: for i in range(len(total)): if typed_words[i] == total[i]: correct.append(typed_words[i]) else: incorrect.append(typed_words[i]) if typed_words[i].lower() == total[i].lower(): wrong_case.append(typed_words[i]) for i in range(1, len(typed_words) - len(total)): excess_words.append(typed_words[-i]) for i in excess_words: incorrect.append(i) score = 100 - ((len(incorrect) / len(total)) * 100) self.result.configure( text=f'Accuracy: {round(score) if score > 0 else 0}%\n\n' + f'Wrong Case: {len(wrong_case)}\n\n Excess Words: {len(excess_words)}' ) if score >= 70: color = 'green' word = 'PASS' else: color = 'red' word = 'FAIL' self.remark.configure(text=f"Remark: {word}", fg=color) return True def run(self, name, temp): self.start_text.destroy() self.timer_clicked = True self.textinput.delete(1.0, END) self.textinput.focus() try: while 1: mins, secs = divmod(temp, 60) self.countdown.configure(text='{}:{:02d}'.format(mins, secs)) if temp == 0: self.countdown.configure(text='Time UP') self.textinput.configure(state=DISABLED) self.calculate() return elif temp <= 10: self.countdown.configure(bg='red', fg='white') if self.submitted == True: self.calculate() return temp -= 1 sleep(1) self.master.update() except RuntimeError: print('MASTER TYPING HAS BEEN CLOSED') except TclError: print('MASTER TYPING HAS BEEN CLOSED') def count(self, event): if not self.timer_clicked: _thread.start_new_thread(self.run, ('Timer', self.temp)) def restart(self): self.master.destroy() main() def level_change(self): if not self.timer_clicked: if self.level_var.get() == 'Easy': self.temp = self.temp + 30 colour = 'green' elif self.level_var.get() == 'Normal': self.temp = self.essay[1] colour = 'orange' else: self.temp -= 30 colour = 'red' minutes = self.temp // 60 seconds = self.temp % 60 self.difficulty.configure( text=f'Difficulty: {self.level_var.get()}', fg=colour) self.countdown.configure( text='{}:{:02d}'.format(minutes, (seconds))) self.master.update() def show_tips(self): showinfo(title='Tip', message=next(self.tips))
class Console(tkinter.Frame): def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs) self.console = ScrolledText(self, bg=Theme.CONSOLE_BG, wrap=tkinter.CHAR, width=40, height=10, state='disabled') # Despite setting height above, this widget gets expanded fully, # if the canvas is smaller than the height, will look odd. self.console.pack(fill=tkinter.BOTH, expand=True) # Text color self.console.tag_config('TEXT', foreground=Theme.HL, font='bold') # Logging colors self.console.tag_config('INFO', foreground=Theme.LOG_INFO) self.console.tag_config('DEBUG', foreground=Theme.LOG_DEBUG) self.console.tag_config('ERROR', foreground=Theme.LOG_ERROR) self.console.tag_config('WARNING', foreground=Theme.LOG_WARNING) self.console.tag_config('CRITICAL', foreground=Theme.LOG_CRITICAL) self.console.focus() self.after(100, self.pooling) def pooling(self): while 1: try: message = QUEUE.get(block=False) self.insert(message) except queue.Empty: break self.after(100, self.pooling) def insert(self, text): self.console.configure(state='normal') # Allow writing try: # Tcl can't render some characters if isinstance(text, Message): self.console.tag_config(text.sender, font='bold', foreground=text.tags.get('color', 'lightblue1')) self.console.insert(tkinter.END, text.sender, text.sender) self.console.insert(tkinter.END, f': {text.message}\n', 'TEXT') else: message = LOGGER.handlers[1].format(text) # This is not a good way to access this self.console.insert(tkinter.END, f'{message}\n', text.levelname) except tkinter.TclError as e: if isinstance(text, Message): # Replace every char outside of Tcl's allowed range with the ? char. text.message = ''.join((ch if ord(ch) <= 0xFFFF else '\uFFFD') for ch in text.message) self.console.insert(tkinter.END, f': {text.message}\n', 'TEXT') else: self.console.insert(tkinter.END, f'{e}\n', 'ERROR') self.console.configure(state='disabled') # Disallow writing self.console.yview(tkinter.END)
Label(tk, text='Output Path').grid(row=3, column=0, sticky='e', ipadx=10) outputPathEntry = Entry(tk, textvariable=outputPathVar) outputPathEntry.grid(row=3, column=1, sticky='w', ipadx=250) outputPathButton = Button(tk, text='Select', width=8, command=lambda: selectoutputPath(outputPathVar)) outputPathButton.grid(row=3, column=2, sticky='w') Label(tk, text='Mel Command').grid(row=4, column=0, sticky='ne', ipadx=10) melCommandScrolledText = ScrolledText(tk, width='80', height='8', wrap='word') melCommandScrolledText.insert(1.0, exportABCAll) melCommandScrolledText.grid(row=4, column=1, sticky='we', columnspan=2) melCommandScrolledText.focus() Label(tk, text='( Maya 文件路径不支持中文和空格)', fg='SaddleBrown').grid(row=5, column=1, sticky='w') localConvertButton = Button(tk, text='Local Convert', fg='green', width=15, command=lambda: ExecuteCmd(1)) localConvertButton.grid(row=6, column=1, sticky='w') submitToDeadlineButton = Button(tk, text='Submit to Deadline', fg='green', width=20, command=lambda: ExecuteSubmitDeadline(1)) submitToDeadlineButton.grid(row=6, column=1, sticky='w', padx=130)
videoFilesEntry = Entry(tk, textvariable=videoFilesVar) videoFilesButton = Button(tk, text='Select', command=lambda: selectVideoFiles(videoFilesVar)) # outputPathLabel = Label(tk, text='Output Path') outputPathEntry = Entry(tk, textvariable=outputPathVar) outputPathButton = Button(tk, text='Select', command=lambda: selectOutputPath(outputPathVar)) # ffmpegLabel = Label(tk, text='FFmpeg Param') ffmpegParam = ScrolledText(tk, width='78', height='6', wrap='word') ffParam = r'-f mpegts -muxrate 9M -b:v 8M -maxrate:v 8M -bufsize:v 8M -profile:v high -level:v 4.0 -c:v libx264 -pix_fmt yuv420p -sc_threshold 0 -g 25 -r 25 -refs 3 -x264-params bframes=2:b-adapt=0:force-cfr=1:b-pyramid=0:nal-hrd=cbr -c:a aac -ar 48000 -b:a 128k -ac 2 -flags +ilme+ildct -top 1' ffmpegParam.insert(1.0, ffParam) ffmpegParam.focus() # ConvertButton = Button( tk, text='Start', fg='green', command=lambda: outputAllVideos(ffmpegInstallPath.get(), videoFilesEntry.get(), ffmpegParam.get(1.0, END), outputPathEntry.get(), 'ts', export=1)) AboutButton = Button(tk, text='About', command=lambda: about.about()) ### tk界面布局 ffmpegInstallPathLabel.grid(row=0, column=0, sticky='e', ipadx=10)
class Console(tkinter.Frame): def __init__(self, parent, settings, max_lines=200, **kwargs): super().__init__(parent, **kwargs) self.settings = settings self.max_lines = max_lines self.console = ScrolledText(self, bg=Theme.CONSOLE_BG, highlightbackground=Theme.BG, highlightcolor=Theme.BG, wrap=tkinter.CHAR, width=40, height=10, state='disabled', relief='flat') # Despite setting height above, this widget gets expanded fully, # if the canvas is smaller than the height, will look odd. self.console.pack(fill=tkinter.BOTH, expand=True) self.font = ('Helvetica', 11, 'bold') # Text color self.console.tag_config('TEXT', foreground=Theme.CONSOLE_TEXT, font=('Helvetica', 11), spacing1=5, spacing3=5) self.console.tag_config('TEXT_ALT', foreground=Theme.CONSOLE_TEXT, background=Theme.CONSOLE_BG_ALT, selectbackground='SystemHighlight', font=('Helvetica', 11), spacing1=5, spacing3=5) # Why does setting 'background' causes highlighted text color to be transparent? # https://web.archive.org/web/20201112014139id_/https://effbot.org/tkinterbook/tkinter-widget-styling.htm self.alt_bg = False # Logging colors self.console.tag_config('INFO', foreground=Theme.LOG_INFO) self.console.tag_config('DEBUG', foreground=Theme.LOG_DEBUG) self.console.tag_config('ERROR', foreground=Theme.LOG_ERROR) self.console.tag_config('WARNING', foreground=Theme.LOG_WARNING) self.console.tag_config('CRITICAL', foreground=Theme.LOG_CRITICAL) self.console.focus() if not self.settings['irc']['username']: self.welcome() self.after(100, self.pooling) def pooling(self): while 1: try: message = QUEUE.get(block=False) self.insert(message) except queue.Empty: break self.after(100, self.pooling) def insert(self, text): self.console.configure(state='normal') # Allow writing try: # Tcl can't render some characters if isinstance(text, Message): self.alt_bg = not self.alt_bg user_color = 'lightblue1' if not text.tags.get('color') else text.tags.get('color') username_tag = f'{text.sender}{"alt_bg" if self.alt_bg else ""}' self.console.tag_config(username_tag, font=self.font, foreground=user_color, background=Theme.CONSOLE_BG_ALT if self.alt_bg else Theme.CONSOLE_BG, selectbackground='SystemHighlight', spacing1=5, spacing3=5) self.console.insert(tkinter.END, text.sender, username_tag) self.console.insert(tkinter.END, f': {text.message}\n', 'TEXT_ALT' if self.alt_bg else 'TEXT') else: message = LOGGER.handlers[1].format(text) # This is not a good way to access this self.console.insert(tkinter.END, f'{message}\n', text.levelname) except tkinter.TclError as e: if isinstance(text, Message): # Replace every char outside of Tcl's allowed range with the ? char. text.message = ''.join((ch if ord(ch) <= 0xFFFF else '\uFFFD') for ch in text.message) self.console.insert(tkinter.END, f': {text.message}\n', 'TEXT') else: self.console.insert(tkinter.END, f'{e}\n', 'ERROR') #https://stackoverflow.com/questions/4609382/getting-the-total-number-of-lines-in-a-tkinter-text-widget self.line_count = int(self.console.index('end-2c').split('.')[0]) if self.line_count > self.max_lines: self.console.delete(1.0, 2.0) self.console.configure(state='disabled') # Disallow writing self.console.yview(tkinter.END) def welcome(self): self.font = ('TkDefaultFont', 11, 'bold') self.console.tag_configure('lightblue', foreground='lightblue1', font=self.font, justify='center') self.console.tag_configure('white', foreground='white', font=self.font) self.console.tag_configure('orange', foreground='orange', font=self.font) self.console.tag_configure('pink', foreground='#FFC8D7', font=self.font) self.console.tag_configure('red', foreground='red', font=self.font, spacing1=2, spacing3=2) self.console.tag_config('grey', foreground='grey', font=('TkDefaultFont', 8, 'bold')) self.console.configure(state='normal') self.console.insert(tkinter.END, '~ Welcome to parky\'s twitch bot! ~\n\n', 'lightblue') self.console.insert(tkinter.END, '\n', 'white') self.console.insert(tkinter.END, 'Quick setup:\n', 'orange') self.console.insert(tkinter.END, '\n', 'white') self.console.insert(tkinter.END, '1', 'red') self.console.insert(tkinter.END, '. Click on the "', 'white') self.settings_img = tkinter.PhotoImage(data=Theme.SETTINGS_ICON) self.console.image_create(tkinter.END, image=self.settings_img) self.console.insert(tkinter.END, '" button.\n', 'white') self.console.insert(tkinter.END, '2', 'red') self.console.insert(tkinter.END, '. Fill in IRC fields to gain chat access!\n', 'white') self.console.insert(tkinter.END, '3', 'red') self.console.insert(tkinter.END, '. ', 'white') self.console.insert(tkinter.END, 'Fill in Twitch API to gain access to channel metadata, such as current title, game, uptime, followers... ', 'white') self.console.insert(tkinter.END, '(optional)\n', 'grey') self.console.insert(tkinter.END, '\n', 'TEXT') self.console.configure(state='disabled')
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'
@@demo aniwave Animated wave @@demo pendulum Pendulum simulation @@demo goldberg A celebration of Rube Goldberg @@subtitle Miscellaneous @@demo bitmap The built-in bitmaps @@demo dialog1 A dialog box with a local grab @@demo dialog2 A dialog box with a global grab """) ############################################################################## ##.t configure -state disabled ##focus .s t['state'] = 'disabled' t.focus() # addSeeDismiss -- # Add "See Code" and "Dismiss" button frame, with optional "See Vars" # # Arguments: # w - The name of the frame to use. ##proc addSeeDismiss {w show {vars {}} {extra {}}} { ## ## See Code / Dismiss buttons ## ttk::frame $w ## ttk::separator $w.sep ## #ttk::frame $w.sep -height 2 -relief sunken ## grid $w.sep -columnspan 4 -row 0 -sticky ew -pady 2 ## ttk::button $w.dismiss -text [mc "Dismiss"] \ ## -image ::img::delete -compound left \
Sizegrip(status_bar).pack(side='right') # 'Sizegrip' displays a lower right corner, making it easier to resize the editor window. # ===================================== # **** Text area **** text_entry = ScrolledText(root, relief='flat', bd=2, wrap='word', undo=1, padx=3, pady=3, font=("Tahoma", "12")) text_entry.pack(expand=True, fill='both') text_entry.focus() # ScrolledText is a Text widget with an implemented vertical scroll bar. # ===================================== # **** keyboard shortcuts **** text_entry.bind('<Control-n>', new_file) text_entry.bind('<Control-N>', new_file) text_entry.bind('<Control-o>', open_file) text_entry.bind('<Control-O>', open_file) text_entry.bind('<Control-s>', save_file) text_entry.bind('<Control-S>', save_file) text_entry.bind('<Control-Shift-s>', save_as_file) text_entry.bind('<Control-Shift-S>', save_as_file) #text_entry.bind('<Control-a>') #text_entry.bind('<Control-A>')
class Editor: def __init__(self, master=None, parent=None): self.parent = parent # ViewMetka self.master = master # Frame self.img_ = parent.img_ font = ("Helvetica", 12) # 24 self.st = ScrolledText(master, height=12, width=40, # height=10 font=font, bg='#777', fg='yellow', wrap=tk.WORD) # tk.NONE # self.st.pack(fill=tk.BOTH, expand=True) # self.st.pack(fill=tk.Y, expand=False) self.st.focus() ttk.Separator(master).pack(fill=tk.X, expand=True) self.dirinfo = tk.StringVar() f = ttk.Frame(master) f.pack(side=tk.BOTTOM, fill=tk.X, expand=True) self.st.pack(side=tk.TOP, fill=tk.BOTH, expand=True) fdir = ttk.Frame(f, padding=1, relief=tk.SUNKEN) fdir.pack(side=tk.LEFT, fill=tk.X, expand=True) ttk.Label(fdir, image=self.img_['folder'], compound=tk.LEFT, textvariable=self.dirinfo, width=9, padding=(2, 2)).pack(side=tk.LEFT, fill=tk.X, expand=True) ttk.Separator(f, orient=tk.VERTICAL).pack(side=tk.LEFT, fill=tk.Y) ttk.Sizegrip(f).pack(side=tk.RIGHT, padx=3) fhelp = ttk.Frame(f, padding=1, relief=tk.SUNKEN) fhelp.pack(side=tk.RIGHT, fill=tk.X, expand=False) btn_cancel = ttk.Button(fhelp, text="Отмена", image=self.img_['delete3'], cursor="hand2", compound=tk.LEFT, command=self.cancel_) self.btn_save = ttk.Button(fhelp, text="Сохранить", image=self.img_['saveas'], cursor="hand2", compound=tk.LEFT, command=self.save_) self.btn_save.pack(side=tk.RIGHT, fill=tk.X, expand=False) btn_cancel.pack(side=tk.RIGHT, fill=tk.X, expand=False) self.btn_db_show = ttk.Button(fhelp, text="Просмотр", image=self.img_['pdf1'], state='disabled', cursor="hand2", compound=tk.LEFT, command=lambda: self.db_show(1)) self.btn_db_print = ttk.Button(fhelp, text="Печать", image=self.img_['print1'], state='disabled', cursor="hand2", compound=tk.LEFT, command=lambda: self.db_show(0)) self.btn_db_show.pack(side=tk.RIGHT, fill=tk.X, expand=False) self.btn_db_print.pack(side=tk.RIGHT, fill=tk.X, expand=False) def db_show(self, verbose, arg=None): """Просмотр или печать базы отметок""" data = self.parent.result command = 'open' if verbose else 'print' cur_path = pathlib.Path('db_op.pdf') tmp_name = cur_path.joinpath(bakdir, cur_path) go_pdf(data, tmp_name) try: os.startfile(f'{tmp_name}', command) # os.startfile('db_op.pdf', command) except: pass def gettext(self): """Получить текст из редактора""" return self.st.get('1.0', tk.END+'-1c') def clrtext(self): """Очистить редактор""" self.st.delete('1.0', tk.END) def set_info(self, msg): """Вывести msg в правый лабель""" return self.dirinfo.set(msg) def cancel_(self, arg=None): """Скрыть редактор""" self.st.delete(1.0, tk.END) self.parent.ed_frame.grid_remove() geom = self.parent.geometry().split("+") self.parent.geometry(f"1051x300+{geom[1]}+{geom[-1]}") def save_(self, arg=None): text = self.gettext() self.parent.save_coment(text)
class EditorWindow: def __init__(self): self.root = Tk(className="EDITOR") self.python_files = PythonFiles(self) self.root.geometry("%dx%d+%d+%d" % ( self.root.winfo_screenwidth() * 0.5, self.root.winfo_screenheight() * 0.4, # self.root.winfo_screenwidth() * 0.1, self.root.winfo_screenheight() * 0.1 0, 0)) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.base_title = "PyEditor v%s" % __version__ self.root.title(self.base_title) self.text_frame = Frame(master=self.root) self.text = ScrolledText(master=self.root, background="white") self.text.bind("<Tab>", self.tab_event) self.text.grid(row=0, column=0, sticky=NSEW) #TODO: find a right height self.exec_output = ScrolledText(master=self.root, height=10, state=DISABLED, background="#dddddd") # for information text like load/save/run: self.exec_output.tag_config( "info", foreground="#0000ff", #background="#eeeeee" ) self.exec_output.grid(row=1, column=0, sticky=NSEW) self.text.focus_set() # self.script_list = ScriptList(self) p = Percolator(self.text) d = ColorDelegator() p.insertfilter(d) # add statusbar to window self.init_statusbar() # add menu to window self.init_menu() # Add special RPi/Minecraft features, if available self.rpi = MinecraftSpecials(self) if self.rpi.mcpi_available: # minecraft is available self.set_content(DEFAULT_MCPI_SCRIPT) if not self.rpi.is_running: self.rpi.startup_minecraft() else: # no minecraft available self.set_content(DEFAULT_SCRIPT) self.root.update() ########################################################################### # Status bar FILENAME_LABEL = "filename" def get_filename(self): filename = self.status_bar.get_textEntry(self.FILENAME_LABEL) return filename def set_filename(self, filename): filename = os.path.split(filename)[-1] self.status_bar.set_textEntry(self.FILENAME_LABEL, filename) def update_filename(self, event=None): filename = self.get_filename() if filename and not filename.endswith(".py"): filename = "%s.py" % filename self.set_filename(filename) def init_statusbar(self): self.status_bar = MyMultiStatusBar(self.root) if sys.platform == "darwin": # Insert some padding to avoid obscuring some of the statusbar # by the resize widget. self.status_bar.set_label('_padding1', ' ', side=RIGHT) self.status_bar.grid(row=2, column=0) self.text.bind("<<set-line-and-column>>", self.set_line_and_column) self.text.event_add("<<set-line-and-column>>", "<KeyRelease>", "<ButtonRelease>") self.text.after_idle(self.set_line_and_column) self.status_bar.new_textEntry(self.FILENAME_LABEL, 'unnamed.py', callback=self.update_filename) def set_line_and_column(self, event=None): line, column = self.text.index(INSERT).split('.') self.status_bar.set_label('column', 'Column: %s' % column) self.status_bar.set_label('line', 'Line: %s' % line) ########################################################################### # Menu def init_menu(self): self.menubar = Menu(self.root) filemenu = Menu(self.menubar, tearoff=0) self.menubar.add_command(label="Run", command=self.command_run) self.menubar.add_command(label="Load", command=self.command_load_file) # filemenu.add_command(label="Load", command=self.command_load_file) self.menubar.add_command(label="Save", command=self.command_save_file) self.menubar.add_command(label="Exit", command=self.root.quit) # # self.menubar.add_cascade(label="File", menu=filemenu) self.root.config(menu=self.menubar) def command_run(self): source_listing = self.get_content() self.exec_output.config(state=NORMAL) self.exec_output.delete("1.0", END) filename = self.get_filename() self.python_files.run_source_listing(source_listing, filename) log.debug("Adding to terminal out") #self.exec_output.insert(END, "Run Script") self.exec_output.config(state=DISABLED) def command_load_file(self): infile = askopenfile( parent=self.root, mode="r", title="Select a Python file to load", filetypes=DEFAULT_FILETYPES, initialdir=BASE_PATH, ) if infile is not None: source_listing = infile.read() infile.close() self.set_content(source_listing) self.set_filename(infile.name) # FIXME: insert only name! self.append_feedback_to_output("Script %r loaded." % infile.name) def command_save_file(self): self.update_filename() # FIXME: add .py if missing content = self.get_content() filename = self.get_filename() filepath = os.path.join(BASE_PATH, filename) if os.path.isfile(filepath): self.python_files.move_to_backup(filepath) with open(filepath, "w") as f: f.write(content) self.append_feedback_to_output("Save to: %r" % filepath) ########################################################################### def get_content(self): content = self.text.get("1.0", END) content = content.strip() return content def set_content(self, source_listing): self.text.delete("1.0", END) log.critical("insert %i Bytes listing.", len(source_listing)) self.text.insert(END, source_listing) self.text.mark_set(INSERT, '1.0') # Set cursor at start self.text.focus() def append_exec_output(self, text): self.exec_output.config(state=NORMAL) self.exec_output.insert(END, text) self.exec_output.config(state=DISABLED) def append_feedback_to_output(self, text): text = "%s\n" % text.rstrip() self.exec_output.config(state=NORMAL) self.exec_output.insert(END, text, "info") self.exec_output.config(state=DISABLED) ########################################################################### indent_pad = " " * 4 def tab_event(self, event): log.debug("Tab event") self.text.insert("insert", self.indent_pad) return BREAK
class PiDiteur(Frame): def __init__(self, parent=None, nom_fichier=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.fichier_courant = nom_fichier self.nom_editeur = self.__class__.__name__ self.creer_composants() self.gerer_evenements() self.afficher_fichier(nom_fichier) def creer_composants(self): self.creer_zone_texte() self.creer_barre_menu() self.creer_barre_texte() def creer_zone_texte(self): self.zone_texte = ScrolledText( self, padx=5, pady=5, wrap=WORD, relief=SUNKEN, font=('courier', 14, 'normal'), bg='white', fg='black', undo=True, autoseparators=True, ) self.zone_texte.pack(side=TOP, fill=BOTH, expand=YES) def creer_barre_texte(self): self.barre_texte = Label(self, relief=SUNKEN, bd=2) self.barre_texte.pack(side=BOTTOM, fill=X) def creer_barre_menu(self): self.barre_menu = Menu(self.master) self.master.config(menu=self.barre_menu) self.menu_fichier() self.menu_editer() def menu_fichier(self): menu = Menu(self.barre_menu, tearoff=False) menu.add_command(label='Ouvrir (Ctrl+o)', command=self.ouvrir) menu.add_command(label='Nouveau (Ctrl+n)', command=self.afficher_fichier) menu.add_command(label='Enregistrer (Ctrl+s)', command=self.enregistrer) menu.add_command(label='Enregistrer sous', command=self.enregistrer_sous) menu.add_command(label='Fermer (Alt+F4)', command=self.quitter) self.barre_menu.add_cascade(label='Fichier', menu=menu) def menu_editer(self): menu = Menu(self.barre_menu, tearoff=False) menu.add_command(label='Couper (Ctrl+x)', command=lambda: self.copier(True)) menu.add_command(label='Copier (Ctrl+c)', command=self.copier) menu.add_command(label='Coller (Ctrl+v)', command=self.coller) menu.add_command(label='Chercher (Ctrl+f)', command=self.chercher) self.barre_menu.add_cascade(label='Edition', menu=menu) def gerer_evenements(self): self.master.bind('<Control-Key-f>', lambda ev: self.chercher()) self.master.bind('<Control-Key-o>', lambda ev: self.ouvrir()) self.master.bind('<Control-Key-s>', lambda ev: self.enregistrer()) self.master.bind('<Control-Key-n>', lambda ev: self.afficher_fichier()) self.master.protocol("WM_DELETE_WINDOW", self.quitter) def afficher_fichier(self, nom_fichier=None): if nom_fichier: with open(nom_fichier, 'r', encoding='utf-8') as f: texte = f.read() self.barre_texte.config(text=nom_fichier) self.master.title('%s - %s' % (self.nom_editeur, nom_fichier)) else: texte = '' nouveau = 'Nouveau fichier' self.barre_texte.config(text=nouveau) self.master.title('%s - %s' % (self.nom_editeur, nouveau)) self.fichier_courant = nom_fichier self.zone_texte.delete('0.0', END) self.zone_texte.insert('0.0', texte) self.zone_texte.mark_set(INSERT, '0.0') self.zone_texte.focus() self.update() def ouvrir(self): fichier = askopenfilename() if fichier: self.afficher_fichier(nom_fichier=fichier) def enregistrer(self): if not self.fichier_courant: fichier = asksaveasfilename() if fichier: self.fichier_courant = fichier else: return fichier = self.fichier_courant texte = self.zone_texte.get('0.0', END) with open(fichier, 'w', encoding='utf-8') as f: f.write(texte) self.barre_texte.config(text=fichier) self.master.title('%s - %s' % (self.nom_editeur, fichier)) def enregistrer_sous(self): fichier = asksaveasfilename() if fichier: self.fichier_courant = fichier self.enregistrer() def copier(self, couper=False): try: texte = self.zone_texte.get(SEL_FIRST, SEL_LAST) except TclError: showinfo(message='Selectionnez du texte à copier !') return if couper: self.zone_texte.delete(SEL_FIRST, SEL_LAST) self.clipboard_clear() self.clipboard_append(texte) def coller(self): try: texte = self.selection_get(selection='CLIPBOARD') self.zone_texte.insert(INSERT, texte) except TclError: pass def chercher(self): caractere = askstring('Recherche', 'Tapez votre chaîne de caractères :') if caractere: trouve = self.zone_texte.search(caractere, INSERT, END) if trouve: aprestrouve = trouve + ('+%dc' % len(caractere)) self.zone_texte.tag_add(SEL, trouve, aprestrouve) self.zone_texte.mark_set(INSERT, aprestrouve) self.zone_texte.see(INSERT) self.zone_texte.focus() def quitter(self): if askyesno( 'Confirmation', 'Voulez-vous vraiment fermer {0} ?'.format(self.nom_editeur)): Frame.quit(self)
class Principal(): def __init__(self, janela): # Funções do menu def Sair(): self.janela.destroy() # Configurações do menu self.janela = janela self.janela = janela self.menubar = Menu(self.janela) self.janela.config(menu=self.menubar) self.Menu_1 = Menu(self.menubar) self.Menu_2 = Menu(self.menubar) self.Menu_3 = Menu(self.menubar) self.menubar.add_cascade(label='Janela', menu=self.Menu_1) self.menubar.add_cascade(label='Arquivo', menu=self.Menu_2) self.Menu_1.add_command(label='Sair', command=Sair) self.Menu_2.add_command(label='Abrir', command=self.NovoArquivo) self.Menu_2.add_command(label='Salvar') self.Menu_2.add_command(label='Adicionar pasta', command=self.AdicionarPasta) # Corpo do programa self.TituloUm = Label(self.janela, text='Selecione o arquivo ou diretorio:') self.EntradaLocal = ScrolledText(self.janela, relief='solid') self.EntradaLocal.focus() self.BotaoSelecionar = Button(self.janela, text='...', borderwidth='0.5', relief='solid', command=self.NovoArquivo) self.BotaoProcessar = Button(self.janela, text='Processar arquivos', bg='#008000', fg='#fff', borderwidth='0.5', relief='solid', command=lambda : self.ProcessarTexto(self.EntradaLocal)) # Posição dos widgets self.TituloUm.place(x=5,y=0, width=170, height=30) self.EntradaLocal.place(x=5,y=30, width=550, height=50) self.BotaoSelecionar.place(x=555,y=30,width=55, height=50) self.BotaoProcessar.place(x=660,y=5,width=120, height=30) self.janela.mainloop() def NovoArquivo(self): self.EntradaLocal.delete('1.0',END) self.LocalArquivo = filedialog.askopenfilename(initialdir = "o:/captura/",title = "Informe o arquivo PDF do Edital",filetypes = (("Arquivos PDF","*.pdf"),("Todos os Arquivos","*.*"))) self.EntradaLocal.insert(END,self.LocalArquivo + '\n') def AdicionarPasta(self): self.LocalPasta = filedialog.askdirectory() Arquivos = os.listdir(self.LocalPasta) for Arquivo in Arquivos: self.EntradaLocal.insert(END,self.LocalPasta + '/' + Arquivo + '\n') def ProcessarTexto(self,Local): self.Local = Local TextoPDF = PegarTexto(self.Local) for Paginas in TextoPDF: processado = open('Resultado\\'+NomeArquivo+'.txt', 'a') #Decomentar somente quando querer os dados em um só arquivo #processado = open('Resultado\\Resultado.txt', 'a') processado.write(str(NomeArquivo)+str(Paginas)) processado.close() def ProcessarImagens(self): ExtrairImagens(self.Local)
mainImage = PhotoImage( file= "~/Documents/GitHub/My-Repo/Tkinter Projects/NotePad+ Files/NotePad+ png images/NotePad0.png" ) base.tk.call('wm', 'iconphoto', base._w, mainImage) fileName = 'Untitled' base.title(f"{fileName} - NotePad+") Store = StringVar() status = 0 # Text Field textField = ScrolledText(base, height=1, width=2, font=('Arial', 16)) textField.pack(anchor=N, fill=BOTH, expand=True) textField.config(wrap='none') textField.focus() #ScrollBars scrollBar = Scrollbar(base, orient="horizontal", command=textField.xview) scrollBar.pack(side=BOTTOM, anchor=S, fill=X) textField["xscrollcommand"] = scrollBar.set def saveasFile(event='<Control-S>'): dateandtime = dt.datetime.now() global fileName file = fd.asksaveasfile(initialfile=fileName, defaultextension=".txt", filetypes=[ ("All Files", "*.*"), ("Text File", "*.txt"), ('Python Source File', '*.py'),
class PiDiteur(Frame): def __init__(self, parent=None, nom_fichier=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.fichier_courant = nom_fichier self.nom_editeur = self.__class__.__name__ self.creer_composants() self.gerer_evenements() self.afficher_fichier(nom_fichier) def creer_composants(self): self.creer_zone_texte() self.creer_barre_menu() self.creer_barre_texte() def creer_zone_texte(self): self.zone_texte = ScrolledText( self, padx=5, pady=5, wrap=WORD, relief=SUNKEN, font=("courier", 14, "normal"), bg="white", fg="black", undo=True, autoseparators=True, ) self.zone_texte.pack(side=TOP, fill=BOTH, expand=YES) def creer_barre_texte(self): self.barre_texte = Label(self, relief=SUNKEN, bd=2) self.barre_texte.pack(side=BOTTOM, fill=X) def creer_barre_menu(self): self.barre_menu = Menu(self.master) self.master.config(menu=self.barre_menu) self.menu_fichier() self.menu_editer() def menu_fichier(self): menu = Menu(self.barre_menu, tearoff=False) menu.add_command(label="Ouvrir (Ctrl+o)", command=self.ouvrir) menu.add_command(label="Nouveau (Ctrl+n)", command=self.afficher_fichier) menu.add_command(label="Enregistrer (Ctrl+s)", command=self.enregistrer) menu.add_command(label="Enregistrer sous", command=self.enregistrer_sous) menu.add_command(label="Fermer (Alt+F4)", command=self.quitter) self.barre_menu.add_cascade(label="Fichier", menu=menu) def menu_editer(self): menu = Menu(self.barre_menu, tearoff=False) menu.add_command(label="Couper (Ctrl+x)", command=lambda: self.copier(True)) menu.add_command(label="Copier (Ctrl+c)", command=self.copier) menu.add_command(label="Coller (Ctrl+v)", command=self.coller) menu.add_command(label="Chercher (Ctrl+f)", command=self.chercher) self.barre_menu.add_cascade(label="Edition", menu=menu) def gerer_evenements(self): self.master.bind("<Control-Key-f>", lambda ev: self.chercher()) self.master.bind("<Control-Key-o>", lambda ev: self.ouvrir()) self.master.bind("<Control-Key-s>", lambda ev: self.enregistrer()) self.master.bind("<Control-Key-n>", lambda ev: self.afficher_fichier()) self.master.protocol("WM_DELETE_WINDOW", self.quitter) def afficher_fichier(self, nom_fichier=None): if nom_fichier: with open(nom_fichier, "r", encoding="utf-8") as f: texte = f.read() self.barre_texte.config(text=nom_fichier) self.master.title("%s - %s" % (self.nom_editeur, nom_fichier)) else: texte = "" nouveau = "Nouveau fichier" self.barre_texte.config(text=nouveau) self.master.title("%s - %s" % (self.nom_editeur, nouveau)) self.fichier_courant = nom_fichier self.zone_texte.delete("0.0", END) self.zone_texte.insert("0.0", texte) self.zone_texte.mark_set(INSERT, "0.0") self.zone_texte.focus() self.update() def ouvrir(self): fichier = askopenfilename() if fichier: self.afficher_fichier(nom_fichier=fichier) def enregistrer(self): if not self.fichier_courant: fichier = asksaveasfilename() if fichier: self.fichier_courant = fichier else: return fichier = self.fichier_courant texte = self.zone_texte.get("0.0", END) with open(fichier, "w", encoding="utf-8") as f: f.write(texte) self.barre_texte.config(text=fichier) self.master.title("{} - {}".format(self.nom_editeur, fichier)) def enregistrer_sous(self): fichier = asksaveasfilename() if fichier: self.fichier_courant = fichier self.enregistrer() def copier(self, couper=False): try: texte = self.zone_texte.get(SEL_FIRST, SEL_LAST) except TclError: showinfo(message="Selectionnez du texte à copier !") return if couper: self.zone_texte.delete(SEL_FIRST, SEL_LAST) self.clipboard_clear() self.clipboard_append(texte) def coller(self): try: texte = self.selection_get(selection="CLIPBOARD") self.zone_texte.insert(INSERT, texte) except TclError: pass def chercher(self): caractere = askstring("Recherche", "Tapez votre chaîne de caractères :") if caractere: trouve = self.zone_texte.search(caractere, INSERT, END) if trouve: aprestrouve = trouve + ("+%dc" % len(caractere)) self.zone_texte.tag_add(SEL, trouve, aprestrouve) self.zone_texte.mark_set(INSERT, aprestrouve) self.zone_texte.see(INSERT) self.zone_texte.focus() def quitter(self): if askyesno("Confirmation", f"Voulez-vous vraiment fermer {self.nom_editeur} ?"): Frame.quit(self)
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 KeyboardGui(Tk): def __init__(self, parent, settings): Tk.__init__(self, parent) self.parent = parent self.value = set_or_default(settings, "text", "") self.password = set_or_default(settings, "password", False) self.result = False self.k = Keyboard(settings) if not self.k.language: return self.initialize() def initialize(self): self.top = Toplevel(self) self.top.geometry('0x0+10000+10000') self.top.protocol('WM_DELETE_WINDOW', self.destroy) self.top.bind("<FocusOut>", self.focus_out) self.geometry('{0}x{1}+{2}+{3}'.format(self.k.width, self.k.height, self.k.location_x, self.k.location_y)) self.overrideredirect(True) self.wm_attributes("-topmost", True) self.entry_field_base_frame = None self.input_block_base_frame = None self.general_buttons_base_frame = None self.entry_field_base_frame = self.reload_frame( self, self.entry_field_base_frame, self.k.get_entry_field_height()) self.input_block_base_frame = self.reload_frame( self, self.input_block_base_frame, self.k.get_input_block_height()) self.general_buttons_base_frame = self.reload_frame( self, self.general_buttons_base_frame, self.k.get_general_buttons_height()) self.entry_field_frame = None self.input_block_frame = None self.general_buttons_frame = None self.reload_keyboard() def reload_keyboard(self): self.reload_styles() self.reload_entry_field() self.reload_input_block() self.reload_general_buttons() def set_colors_for_style(self, style): s = ttk.Style() s_map = s.map if self.k.b_customize: s_map = s.map( "{}.TButton".format(style), foreground=[ ('!active', self.k.b_style["b_foreground_!active"]), ('pressed', self.k.b_style["b_foreground_pressed"]), ('active', self.k.b_style["b_foreground_active"]) ], background=[ ('!active', self.k.b_style["b_background_!active"]), ('pressed', self.k.b_style["b_background_pressed"]), ('active', self.k.b_style["b_background_active"]) ]) return s_map def reload_styles(self): # Для кнопок с иконками style_standart = ttk.Style() style_standart.map = self.set_colors_for_style("ScreenButton") # Для кнопок с текстом # Для мальнького шрифта style_small_top = ttk.Style() style_small_center = ttk.Style() style_small_bottom = ttk.Style() style_small_top.map = self.set_colors_for_style("ScreenButtonSmallTop") style_small_top.map = self.set_colors_for_style( "ScreenButtonSmallCenter") style_small_top.map = self.set_colors_for_style( "ScreenButtonSmallBottom") style_small_center.configure('ScreenButtonSmallTop.TButton', font=(self.k.font, self.k.font_size["small"]), anchor=N) style_small_center.configure('ScreenButtonSmallCenter.TButton', font=(self.k.font, self.k.font_size["small"]), anchor=CENTER) style_small_center.configure('ScreenButtonSmallBottom.TButton', font=(self.k.font, self.k.font_size["small"]), anchor=S) # Для нормального шрифта style_normal_top = ttk.Style() style_normal_center = ttk.Style() style_normal_bottom = ttk.Style() style_normal_top.map = self.set_colors_for_style( "ScreenButtonNormalTop") style_normal_top.map = self.set_colors_for_style( "ScreenButtonNormalCenter") style_normal_top.map = self.set_colors_for_style( "ScreenButtonNormalBottom") style_normal_center.configure('ScreenButtonNormalTop.TButton', font=(self.k.font, self.k.font_size["normal"]), anchor=N) style_normal_center.configure('ScreenButtonNormalCenter.TButton', font=(self.k.font, self.k.font_size["normal"]), anchor=CENTER) style_normal_center.configure('ScreenButtonNormalBottom.TButton', font=(self.k.font, self.k.font_size["normal"]), anchor=S) # Для большого шрифта style_large_top = ttk.Style() style_large_center = ttk.Style() style_large_bottom = ttk.Style() style_large_top.map = self.set_colors_for_style("ScreenButtonLargeTop") style_large_top.map = self.set_colors_for_style( "ScreenButtonLargeCenter") style_large_top.map = self.set_colors_for_style( "ScreenButtonLargeBottom") style_large_center.configure('ScreenButtonLargeTop.TButton', font=(self.k.font, self.k.font_size["large"]), anchor=N) style_large_center.configure('ScreenButtonLargeCenter.TButton', font=(self.k.font, self.k.font_size["large"]), anchor=CENTER) style_large_center.configure('ScreenButtonLargeBottom.TButton', font=(self.k.font, self.k.font_size["large"]), anchor=S) def reload_entry_field(self): frame_h = self.k.get_entry_field_height() rows = self.k.get_entry_field_rows() row_h = frame_h / len(rows) self.entry_field_frame = self.reload_frame(self.entry_field_base_frame, self.entry_field_frame, frame_h) self.create_rows(self.entry_field_frame, rows, row_h) self.entry.focus() def reload_input_block(self): frame_h = self.k.get_input_block_height() rows = self.k.get_input_block_rows() row_h = frame_h / len(rows) self.input_block_frame = self.reload_frame(self.input_block_base_frame, self.input_block_frame, frame_h) self.create_rows(self.input_block_frame, rows, row_h) self.entry.focus() def reload_general_buttons(self): frame_h = self.k.get_general_buttons_height() rows = self.k.get_general_buttons_rows() row_h = frame_h / len(rows) self.general_buttons_frame = self.reload_frame( self.general_buttons_base_frame, self.general_buttons_frame, frame_h) self.create_rows(self.general_buttons_frame, rows, row_h) self.entry.focus() def reload_frame(self, base_frame, frame, h): if not frame is None: frame.destroy() frame = Frame(base_frame, bg="white", width=self.k.width, height=h) frame.grid(padx=0, pady=0) return frame def create_rows(self, frame, rows, h): y = 0 for row in rows: self.create_row(frame, row, h, y) y += h def create_row(self, frame, row, h, y): count = 0 x = 0 for el in row: if count == len(row) - 1: w = self.width(el["size"], x, True) else: w = self.width(el["size"]) self.create_el(frame, el, x, y, w, h) x += w count += 1 def create_el(self, frame, el, x, y, w, h): if el["control"] == "button": text = "" icon = "" button = None if el["type"] == "apply": if el["icon"]: self.create_btn_with_icon(frame, el["icon"], x, y, w, h, self.apply) else: self.create_btn_with_text(frame, el["text"], x, y, w, h, self.apply, el["style"]) elif el["type"] == "input": if not self.k.uppercase: self.create_btn_with_text( frame, el["value1"], x, y, w, h, lambda k=el["value1"]: self.input(k), el["style"]) else: self.create_btn_with_text( frame, el["value2"], x, y, w, h, lambda k=el["value2"]: self.input(k), el["style"]) elif el["type"] == "turn": if el["iconTurnOn"] and el["iconTurnOff"]: if el["turnTarget"] == "uppercase": if not self.k.uppercase: self.create_btn_with_icon(frame, el["iconTurnOff"], x, y, w, h, self.switch_case) else: self.create_btn_with_icon(frame, el["iconTurnOn"], x, y, w, h, self.switch_case) elif el["turnTarget"] == "numbers": if not self.k.numbers: self.create_btn_with_icon( frame, el["iconTurnOff"], x, y, w, h, self.switch_input_keyboard) else: self.create_btn_with_icon( frame, el["iconTurnOn"], x, y, w, h, self.switch_input_keyboard) else: if el["turnTarget"] == "uppercase": if not self.k.uppercase: self.create_btn_with_text(frame, el["textTurnOff"], x, y, w, h, self.switch_case, el["style"]) else: self.create_btn_with_text(frame, el["textTurnOn"], x, y, w, h, self.switch_case, el["style"]) elif el["turnTarget"] == "numbers": if not self.k.numbers: self.create_btn_with_text( frame, el["textTurnOff"], x, y, w, h, self.switch_input_keyboard, el["style"]) else: self.create_btn_with_text( frame, el["textTurnOn"], x, y, w, h, self.switch_input_keyboard, el["style"]) elif el["type"] == "languare": if el["icon"]: self.create_btn_with_icon(frame, el["icon"], x, y, w, h, self.switch_language) else: self.create_btn_with_text(frame, self.k.language, x, y, w, h, self.switch_language, el["style"]) elif el["type"] == "action": if el["icon"]: self.create_btn_with_icon( frame, el["icon"], x, y, w, h, lambda a=el["action"]: self.action(a)) else: self.create_btn_with_text( frame, el["text"], x, y, w, h, lambda a=el["action"]: self.action(a), el["style"]) elif el["control"] == "field": if el["type"] == "line": self.create_entry_field(frame, x, y, w, h, self.entry_font_size(el["font"])) elif el["type"] == "multiline": self.create_text_field(frame, x, y, w, h, self.entry_font_size(el["font"])) def create_btn_with_icon(self, frame, icon, x, y, w, h, command): image = Image.open(self.k.icon_path(icon)) maxsize = (w * 0.9, h * 0.7) image.thumbnail(maxsize, Image.ANTIALIAS) photo = ImageTk.PhotoImage(image) button = ttk.Button(frame, image=photo, command=command, style="ScreenButton.TButton") button.photo = photo button.place(x=x, y=y, width=w, height=h) def create_btn_with_text(self, frame, text, x, y, w, h, command, style): button = ttk.Button(frame, text=text, command=command, style="{0}.TButton".format(style)) button.place(x=x, y=y, width=w, height=h) def create_entry_field(self, frame, x, y, w, h, font): self.entry = None if self.password: self.entry = ttk.Entry(frame, show="*", font=font) else: self.entry = ttk.Entry(frame, font=font) self.entry.place(x=x + 1, y=y + 1, width=w - 2, height=h - 2) self.entry.insert(END, self.value) self.entry.focus() def create_text_field(self, frame, x, y, w, h, font): self.entry = ScrolledText(frame, font=font) self.entry.place(x=x + 1, y=y + 1, width=w - 2, height=h - 2) self.entry.insert(END, self.value) self.entry.focus() def entry_font_size(self, font_type): if font_type == "EntryFontSmall": return TkFont.Font(name=self.k.font, size=self.k.font_size["small"]) if font_type == "EntryFontNormal": return TkFont.Font(name=self.k.font, size=self.k.font_size["normal"]) if font_type == "EntryFontLarge": return TkFont.Font(name=self.k.font, size=self.k.font_size["large"]) def width(self, size, used_width=0, last=False): w = 0 if last: w = self.k.width - used_width else: w = self.k.width / 12 * size return w def focus_out(self, event): w = self.focus_get() if w == None: self.exit() else: w.bind("<FocusOut>", self.focus_out) def exit(self): self.get_text() self.top.destroy() self.destroy() def action(self, a): if a == "backspace": if self.k.multiline: try: self.entry.delete("sel.first", "sel.last") except: insert = self.entry.index("insert") line, char = insert.split(".") delindex = "{0}.{1}".format(line, int(char) - 1) self.entry.delete(delindex) else: try: self.entry.delete("sel.first", "sel.last") except: insert = self.entry.index("insert") self.entry.delete(insert - 1) elif a == "enter": if self.k.multiline: try: self.entry.delete("sel.first", "sel.last") except: pass self.entry.insert(INSERT, "\n") def input(self, k): try: self.entry.delete("sel.first", "sel.last") except: pass self.entry.insert(INSERT, k) self.entry.focus() def switch_case(self): self.k.switch_case() self.reload_input_block() self.reload_general_buttons() def switch_input_keyboard(self): self.k.switch_input_keyboard() self.reload_input_block() self.reload_general_buttons() def switch_language(self): self.k.switch_language() self.reload_input_block() self.reload_general_buttons() def apply(self): self.get_text() self.result = True self.top.destroy() self.destroy() def get_text(self): if self.k.multiline: self.value = self.entry.get('1.0', 'end-1c') else: self.value = self.entry.get()
def inputText_Modified(t: ScrolledText): pass def Treeview_Select(evt): pass tk.Label(root, text='Text', font=lf).grid(row=0, column=0, sticky='nw', padx=6, pady=6) inputText = ScrolledText(root, height=4, width=20, wrap=tk.WORD, font=tf) inputText.grid(row=0, column=1, sticky='we', padx=6, pady=6) inputText.focus() inputText.bind('<<Modified>>', lambda event: inputText_Modified(inputText)) buttonsFrame = tk.Frame(root, padx=6, pady=6) buttonsFrame.grid(row=0, column=2, sticky='n') aboutButton = tk.Button(buttonsFrame, text='About', command=about_click) aboutButton.pack(fill=tk.X) root.bind('<F1>', lambda e: about_click()) aboutButton_ttp = TkToolTip(aboutButton, '[F1] Show application information') tk.Button(buttonsFrame, text='Close', command=lambda: tk.Frame.quit(root)).pack(fill=tk.X, pady=6) tk.Label(root, text='Transformations', font=lf).grid(row=1, column=0, sticky='nw', padx=6,
class VentanaContador: def __init__(self): self.html_table = "" self.cabecera = ('N', 'Verso', 'Etiquetado', "Sílabas", "Acentos", 'Sin extrarrítmicos', 'Tipo', 'Coincidencia') self.dibujar() def dibujar(self): self.root = Tk() self.root.title("Jumper: Contador de sílabas y acentos en tiempo real") # Group0 Frame ---------------------------------------------------- group0 = LabelFrame(self.root, text="Tendencia versal", padx=2, pady=2) group0.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group0.rowconfigure(0, weight=1) group0.columnconfigure(0, weight=1) # Create the textbox self.trend = Entry(group0, width=50, font=("Verdana", 11)) self.trend.grid(row=0, column=0, sticky=E + W + N + S) # Group1 Frame ---------------------------------------------------- group1 = LabelFrame(self.root, text="Poema", padx=2, pady=2) group1.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group1.rowconfigure(0, weight=1) group1.columnconfigure(0, weight=1) # Create the textbox self.txt_origen = ScrolledText(group1, width=80, height=10, font=("Times New Roman", 12)) self.txt_origen.grid(row=0, column=0, sticky=E + W + N + S) # Group2 Frame ---------------------------------------------------- group2 = LabelFrame(self.root, text="Análisis", padx=2, pady=2) group2.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group2.rowconfigure(1, weight=1) group2.columnconfigure(0, weight=1) # Create the textbox self.txt_destino = ttk.Treeview(group2, height=25, columns=self.cabecera, show='headings') vsb = ttk.Scrollbar(group2, orient="vertical", command=self.txt_destino.yview) vsb.configure(command=self.txt_destino.yview) self.txt_destino.configure(yscrollcommand=vsb.set) # set column headings tamanios = (50, 400, 400, 80, 180, 180, 350, 100) for i, col in enumerate(self.cabecera): self.txt_destino.heading(col, text=col) self.txt_destino.column(col, minwidth=0, width=tamanios[i], stretch=NO) self.txt_destino.tag_configure('green', foreground='green') self.txt_destino.tag_configure('red', foreground='red') self.txt_destino.tag_configure('black', foreground='black') vsb.grid(row=1, column=3, sticky=N + S) self.txt_destino.grid(row=1, column=0, sticky=E + W + N + S) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(1, weight=1) # Menu menubar = Menu(self.root) self.root.config(menu=menubar) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Guardar análisis", command=self.onSave) filemenu.add_command(label="Limpiar texto", command=self.clearText) filemenu.add_separator() filemenu.add_command(label="Salir", command=self.root.quit) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Cómo se usa", command=self.popupmsgHelp) helpmenu.add_separator() helpmenu.add_command(label="Acerca de...", command=self.popupmsgAbout) analisismenu = Menu(menubar, tearoff=0) analisismenu.add_command(label="Analizar poema", command=self.put_text_in_txt_destino_menu) menubar.add_cascade(label="Archivo", menu=filemenu) menubar.add_cascade(label="Análisis", menu=analisismenu) menubar.add_cascade(label="Ayuda", menu=helpmenu) self.txt_origen.bind('<Button-3>', self.rClicker, add='') self.txt_origen.bind('<KeyPress>', self.put_text_in_txt_destino_on_key) self.txt_origen.focus() self.statusbar = Label(self.root, text="", bd=1, relief=SUNKEN, anchor='e', justify=LEFT) self.statusbar.grid(row=3, column=0, columnspan=2) # https://stackoverflow.com/questions/4266566/stardand-context-menu-in-python-tkinter-text-widget-when-mouse-right-button-is-p def rClicker(self, e): try: def rClick_Copy(e, apnd=0): e.widget.event_generate('<Control-c>') def rClick_Cut(e): e.widget.event_generate('<Control-x>') def rClick_Paste(e): e.widget.event_generate('<Control-v>') e.widget.focus() nclst = [ (' Cortar', lambda e=e: rClick_Cut(e)), (' Copiar', lambda e=e: rClick_Copy(e)), (' Pegar', lambda e=e: rClick_Paste(e)), ] rmenu = Menu(None, tearoff=0, takefocus=0) for (txt, cmd) in nclst: rmenu.add_command(label=txt, command=cmd) rmenu.tk_popup(e.x_root + 40, e.y_root + 10, entry="0") except TclError: print(' - rClick menu, something wrong') pass return "break" def show(self, x, colores): self.txt_destino.delete(*self.txt_destino.get_children()) for i, (v, v_etiquetado, v_silabas, v_acentos, v_extra, v_tipo, v_coin) in enumerate(x): self.txt_destino.insert("", "end", values=(i + 1, v, v_etiquetado, v_silabas, str(v_acentos), str(v_extra), v_tipo, v_coin), tags=(colores[i], )) def put_text_in_txt_destino_on_key(self, event): t = threading.Thread(target=self.put_text_in_txt_destino(), args=(self, )) del (t) def put_text_in_txt_destino_menu(self): t = threading.Thread(target=self.put_text_in_txt_destino(), args=(self, )) del (t) def put_text_in_txt_destino(self): fetched_content = self.txt_origen.get('1.0', 'end-1c') try: x = jumper.escandir_texto(fetched_content) columna_silabas_v = list(map(list, zip(*x)))[2] versos_frecuentes = jumper.most_frequent(columna_silabas_v) except: return None tendencia_versal = self.trend.get().strip().strip(',').split(',') # si hay tendencia versal operamos con ella if tendencia_versal[0] != '' and tendencia_versal[0].find( 'Auto') == -1: tendencia_versal = [ int(i) for i in tendencia_versal ] if len(tendencia_versal) > 0 and self.RepresentsInt( tendencia_versal[0]) else [] else: tendencia_versal = list(versos_frecuentes.keys()) self.trend.delete(0, END) self.trend.insert( 0, 'Auto: ' + str(tendencia_versal).replace(']', '').replace('[', '')) precision = 0 colores = [] self.html_table = '<table width="100%" style="margin: 0px;font-size: 11pt;font-family: Courier;">' self.html_table += '<tr>' for item in self.cabecera: self.html_table += '<th style="text-align: left;">' + item + '</th>' self.html_table += '</tr>' for i, v in enumerate(x): silabas_v = v[2] # se convierte a porcetaje v[-1] = int(v[-1] * 100) if len(tendencia_versal) > 0: if silabas_v in tendencia_versal and v[-1] == 100: precision += 1 color = 'green' elif silabas_v in tendencia_versal: precision += 1 color = 'black' else: color = 'red' colores.append(color) self.html_table += '<tr style="color:' + color + '">' self.html_table += '<td>' + str(i) + '</td>' for item in v: self.html_table += '<td>' + str(item) + '</td>' self.html_table += '</tr>' self.html_table += '</table><br>' self.html_table += 'Tendencia versal: ' + str( tendencia_versal) + '<br>' calidad, regularidad = self.calcular_calidad_precision( x, versos_frecuentes) #imprimimos regularidad y precision resumen_precision = f"Precisión de los acentos: {calidad:.1f}% Regularidad con los versos más frecuentes: {regularidad:.1f}%" self.statusbar['text'] = resumen_precision self.html_table += resumen_precision self.show(x, colores) #self.txt_destino.set_content(self.html_table) def calcular_calidad_precision(self, analisis, versos_frecuentes): calidad = 0 regularidad = 0 for verso_analizado in analisis: ratio = verso_analizado[-1] silabas = verso_analizado[2] if ratio == 100: calidad += 1 if silabas in versos_frecuentes: regularidad += 1 return (calidad / len(analisis)) * 100, (regularidad / len(analisis)) * 100 def popupgen(self, title, msg): popup = Tk() popup.wm_title(title) label = Label(popup, text=msg) label.pack(side="top", fill="x", pady=15) B1 = Button(popup, text="Ok", command=popup.destroy) B1.pack() popup.mainloop() def popupmsgAbout(self): msg = 'Analizador automático de métrica por Guillermo Marco Remón.\n nlp.uned.es, Research Group in NLP & IR, UNED, Madrid, Spain.\n Las tipologías de verso empleadas se han extraído de Pou, P. J. (2020). Métrica española. Ediciones Cátedra. \n Si detecta cualquier error escriba a [email protected]' title = "Acerca de... Versión 21122020" self.popupgen(title, msg) def popupmsgHelp(self): msg = 'Pegue o escriba el poema en la sección "Poema",\nel análisis métrico se hará automáticamente. \nLa tendencia versal se calculará también automáticamente.\n Si lo desea, puede establecerla manualmente separada por comas en la caja de texto: ej.: 14, 11, 7' title = 'Modo de empleo' self.popupgen(title, msg) def clearText(self): self.txt_origen.delete('1.0', END) def onSave(self): home = os.path.expanduser('~') path = filedialog.asksaveasfilename(initialdir=home, title="Guardar como", filetypes=(("html", "*.html"), ("All files", "*.*"))) textFile = open(path + '.html', 'w') textFile.write(self.html_table) textFile.close() def RepresentsInt(self, s): try: int(s) return True except ValueError: return False def lanzar(self): self.root.mainloop()
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(tk.Frame): def __init__(self, pin, master=None): tk.Frame.__init__(self, master) self.master = master self.master.protocol('WM_WINDOW_DELETE', self.exit) self.master.title('SIT210 - Embedded Systems Development') self.pack() self.img = ImageTk.PhotoImage(Image.open('logo.png')) self.createWidgets() self.blinker = morse.Morse(pin) def exit(self): self.master.destroy() def enterMessage(self): message = self.input_box.get('1.0', tk.END) self.blinker.blinkMessage(message) def createWidgets(self): # Prepare fonts std_font = tk.font.Font(family='Helvetica', size=12) ttl_font = tk.font.Font(family='Helvectic', size=16, weight='bold') # Add RPi image self.logo = tk.Label(self.master, image=self.img) self.logo.pack(side="top", fill="x", pady=15, expand="no") # Add Task name label self.label = tk.Label() self.label['text'] = 'Task 5.3D - Blink Morse Code' self.label['font'] = ttl_font self.label.pack(padx=15, pady=10) # Add textbox label self.entry_label = tk.Label() self.entry_label['text'] = 'Enter text to blink' self.entry_label['font'] = std_font self.entry_label['anchor'] = tk.W self.entry_label.pack(padx=15, fill='both') # Add textbox self.input_box = ScrolledText() self.input_box['width'] = 40 self.input_box['height'] = 5 self.input_box['wrap'] = tk.WORD self.input_box.pack(padx=15, fill='both') self.input_box.focus() # Add Enter button self.Enter = tk.Button(self.master) self.Enter['text'] = 'Enter' self.Enter['width'] = 20 self.Enter['command'] = self.enterMessage self.Enter.pack(side=tk.LEFT, padx=15, pady=15) # Add Exit button self.Exit = tk.Button(self.master) self.Exit['text'] = 'Exit' self.Exit['width'] = 20 self.Exit['command'] = self.exit self.Exit.pack(side=tk.LEFT, padx=10, pady=15)
class Toki(tk.Tk): def __init__(self, file=None): super().__init__() self.actions = { 'ENT': '\n', 'BKSP': 'backspace', 'TAB': 'tab', 'HOME': 'home', 'PAGEUP': 'pgup', 'DEL': 'del', 'END': 'end', 'PAGEDOWN': 'pgdn', 'UP': 'up', 'LEFT': 'left', 'DOWN': 'down', 'RIGHT': 'right' } self.insert = False self.file = file self.title('ilo nimi pi sitelen pona') self.menu = tk.Frame(self) self.filemenu = tk.Menubutton(self.menu, font=("sitelen luka tu tu", 14), text='\uE02A') #file self.filemenud = tk.Menu(self.filemenu, tearoff=0) self.filemenud.add_checkbutton( label="\uE02A\uE05D", #new font=("sitelen luka tu tu", 14), command=lambda: Toki().mainloop()) self.filemenud.add_checkbutton( label="o\uE047e\uE02A", #open font=("sitelen luka tu tu", 14), command=self.opennew) self.filemenud.add_separator() self.filemenud.add_checkbutton( label="o\uE009e\uE02A", #save font=("sitelen luka tu tu", 14), command=lambda: self.save(False)) self.filemenud.add_checkbutton( label="o\uE009e\uE02A\uE05D", #save as font=("sitelen luka tu tu", 14), command=lambda: self.save(True)) self.filemenud.add_checkbutton( label="o\uE049e\uE02APDF", #export font=("sitelen luka tu tu", 14), command=self.export) self.filemenud.add_separator() self.filemenud.add_checkbutton( label="o\uE050", #close font=("sitelen luka tu tu", 14), command=self.destroy) self.filemenu["menu"] = self.filemenud self.text = ScrolledText(self, width=40) self.text.configure(font=('sitelen luka tu tu', 20)) self.keyboardFrame = tk.Frame(self, padx=5, pady=5) self.keyboard = Keyboard(self.keyboardFrame) self.menu.pack(expand=tk.YES, fill=tk.X) self.filemenu.grid(row=0) self.keyboardFrame.pack() self.keyboard.grid(row=0) self.text.pack(expand=tk.YES, fill=tk.BOTH) if self.file: self.open(self.file) self.after(0, self.getWord) def getWord(self): words = self.keyboard.getWords() if words: self.text.focus() for w in words: if w in self.actions: pa.press(self.actions[w]) elif w == 'INS': self.insert = not self.insert else: if self.insert: pa.press('del') self.text.insert(tk.INSERT, w) self.after(10, self.getWord) def save(self, new): if new: filename = filedialog.askopenfilename( title="lipu awen li seme?", parent=self, defaultextension='.toki', filetypes=(("lipu Toki", "*.toki"), ("lipu ali", "*.*"))) else: filename = filedialog.asksaveasfilename( title="lipu awen li seme?", parent=self, defaultextension='.toki', filetypes=(("lipu .toki", "*.toki"), ("lipu ali", "*.*"))) if filename: try: with open(filename, 'wb') as f: f.write(self.text.get('1.0', 'end').encode()) self.title('ilo nimi pi sitelen pona: ' + filename) self.file = filename except IOError as e: messagebox.showerror( 'pakala!', 'ni li ike:\nI/O error ({0}): {1}'.format( e.errno, e.strerror)) else: messagebox.showinfo('pona!', 'lipu li awen!') def open(self, filename): try: with open(filename, 'rb') as f: self.text.insert('1.0', f.read().decode()) self.title('ilo nimi pi sitelen pona: ' + filename) self.file = filename except IOError as e: messagebox.showerror( 'pakala!', 'ni li ike:\nI/O error ({0}): {1}'.format(e.errno, e.strerror)) def opennew(self): filename = filedialog.askopenfilename(title="lipu open li seme?", parent=self, defaultextension='.toki', filetypes=(("lipu Toki", "*.toki"), ("lipu ali", "*.*"))) if filename: if self.file: Toki(filename).mainloop() else: self.open(filename) def export(self): filename = filedialog.asksaveasfilename( title="lipu pana li seme?", parent=self, defaultextension='.pdf', filetypes=(("lipu .pdf", "*.pdf"), ("lipu ali", "*.*"))) try: pdf = fpdf.FPDF() pdf.add_page() try: pdf.add_font( 'sitelen luka tu tu', '', (r'C:\Windows\Fonts\sitelen_luka_tu_tu.ttf' if os.name == 'nt' else '/usr/share/fonts/sitelen_luka_tu_tu.ttf'), uni=True) except RuntimeError: pdf.add_font( 'sitelen luka tu tu', '', (r'C:\Windows\Fonts\sitelen_luka_tu_tu.ttf_' if os.name == 'nt' else '/usr/share/fonts/sitelen_luka_tu_tu_.ttf'), uni=True) pdf.set_font('sitelen luka tu tu', size=20) for t in self.text.get('1.0', tk.END).split('\n'): pdf.cell(200, 10, txt=t, ln=1, align='L') pdf.output(filename) except Exception as e: messagebox.showerror('pakala!', 'ni li ike:\n' + str(e)) else: messagebox.showinfo('pona!', 'lipu li pana!')
class myPanel(tkinter.Tk): def __init__(self): tkinter.Tk.__init__(self, 'lsx') self.withdraw() # 先withdraw隐藏再deiconify显示可使setCenter不会导致页面闪烁 self.title('电话簿v1.05 (联系作者:QQ11313213)') # TODO 是否有用 self.keys_var = tkinter.StringVar() self.tex1 = ScrolledText(self) ent1 = tkinter.Entry(self, textvariable=self.keys_var, width=125) ent1.pack(padx=2, pady=2, fill=tkinter.constants.BOTH, side=tkinter.constants.TOP) self.tex1.pack(padx=2, pady=2, fill=tkinter.constants.BOTH, expand=True) self.menu = tkinter.Menu(self, tearoff=0) self.menu.add_command(label='复制', command=self.copyItem) self.menu.add_separator() self.menu.add_command(label='来源') self.menu.add_separator() self.menu.add_command(label='刷新', command=readContacts2) self.menu.add_command(label='前后文', command=self.location) self.menu.add_separator() self.menu.add_command(label='导入文件', command=ImportFiles) self.menu.add_command(label='新增和更改', command=UpdateFile) self.menu0 = tkinter.Menu(self, tearoff=0) self.menu0.add_command(label='刷新', command=readContacts2) self.menu0.add_separator() self.menu0.add_command(label='导入文件', command=ImportFiles) self.menu0.add_command(label='新增和更改', command=UpdateFile) self.menu0.add_separator() submenu = [tkinter.Menu(self, tearoff=0)] self.menu0.add_cascade(label='Designed by Lsx. ', menu=submenu[0]) for key, value in [['Name', 'Li Shixian'], ['Mail', '*****@*****.**'], ['Website', 'github.com/znsoooo/contacts'], ['Wechat', 'Xian_2'], ['Donate', 'xxxx']]: submenu.append(tkinter.Menu(self, tearoff=0)) submenu.append(tkinter.Menu(self, tearoff=0)) submenu[-1].add_command(label=value) submenu[0].add_cascade(label=key, menu=submenu[-1]) self.img_wechat = tkinter.PhotoImage( data=Image.img1) # 没有self会导致显示图片为空白 self.img_donate = tkinter.PhotoImage(data=Image.img2) submenu[8].entryconfig(0, image=self.img_wechat) submenu[10].entryconfig(0, image=self.img_donate) submenu[0].add_separator() submenu[0].add_command(label='All Rights Reserved.', command=bonus) setCenter(self) self.deiconify() ent1.focus() ent1.bind('<KeyRelease>', self.onKeyRelease) self.tex1.bind('<ButtonRelease-3>', self.onRightClick) def select(self, row): self.tex1.mark_set('insert', '%d.0' % row) self.tex1.tag_remove('sel', '0.0', 'end') self.tex1.tag_add('sel', '%d.0' % row, '%d.0' % (row + 1)) def location(self, row=0): if not row: row = self.current_index + 1 self.onKeyRelease(keys='') self.select(row) self.tex1.see('%d.0' % row) def copyItem(self): text = self.tex1.selection_get() self.clipboard_clear() self.clipboard_append(text[:-1]) # 去掉文末换行符 def onRightClick(self, evt=0): self.tex1.focus() # 当焦点在ent1中时 self.current = int(self.tex1.index('current').split('.')[0]) if len(self.index): self.current_index = self.index[self.current - 1] line_last = 0 for line, file in file_list: if line > self.current_index: break else: line_last = line self.menu.entryconfig(2, label='来源: %s (line:%s)' % (file, self.current_index - line_last + 1)) self.menu.entryconfig( 2, command=lambda: os.popen('explorer /select, %s\\%s\\%s' % (os.getcwd(), DATA_FOLDER, file))) self.select(self.current) self.menu.post(evt.x_root, evt.y_root) else: self.menu0.post(evt.x_root, evt.y_root) return self.current def onKeyRelease(self, evt=0, keys=None): if keys is None: keys = self.keys_var.get() keys = keys.lower().split(' ') ss_new = [] self.index = [] for n, s in enumerate(ss): ok = True for key in keys: if key not in s[1]: ok = False if ok: ss_new.append(s[0]) self.index.append(n) # TODO 提出搜索部分到独立的函数 self.tex1.config(state='normal') self.tex1.delete('1.0', 'end') self.tex1.insert('1.0', '\n'.join(ss_new)) self.tex1.config(state='disabled') # 禁止编辑 self.title('电话簿v1.05 (联系作者:QQ11313213) - %s结果' % len(ss_new)) # title更改耗时短可以做到'同时'更改的效果 return ss_new
class NoteEditor: def __init__(self): self.id = None self.page_name = None self.font_name = 'arial' self.font_size = 12 self.font_weight = tk.NORMAL self.editor = None self.file_io = FileIO() self.syntax_file_io = FileIO() def create_editor(self, master): self.editor = ScrolledText(master, undo=True, autoseparators=True, maxundo=-1) # Styling of text area self.set_editor_font(None, None) self.editor.pack(side="left") self.editor.focus() self.editor.pack(fill="both", expand=True) # Configuring style tags self.editor.tag_config("BACKGROUND", background="yellow") self.editor.tag_configure("HIGHLIGHT", foreground="red") self.editor['wrap'] = tk.NONE self.editor.bind('<Button-3>', self.rClicker, add='') def set_editor_font(self, font_name, font_size, font_weight=None): if font_name is not None: self.font_name = font_name if font_size is not None and int(font_size) > 0: self.font_size = font_size if font_weight is not None: self.font_weight = font_weight self.editor['font'] = Font(family=self.font_name, size=self.font_size, weight=self.font_weight) def set_editor_bgcolor(self, hex_color): self.editor['background'] = hex_color def set_editor_fgcolor(self, hex_color): self.editor['foreground'] = hex_color def set_emphasis(self, on): if on == 1: bold_font = Font(family=self.font_name, size=self.font_size, weight="bold") self.editor.tag_configure("BOLDFONT", font=bold_font) if self.editor.tag_ranges(tk.SEL): self.editor.tag_add("BOLDFONT", tk.SEL_FIRST, tk.SEL_LAST) else: self.editor.tag_add("BOLDFONT", "1.0", tk.END) else: self.editor.tag_remove("BOLDFONT", "1.0", tk.END) def toggle_wrap(self, on): if on == 1: self.editor['wrap'] = tk.WORD else: self.editor['wrap'] = tk.NONE def search_forward(self, text): located_start = self.editor.search(text, tk.INSERT, stopindex=tk.END, forwards=True, nocase=True) located_end = '{}+{}c'.format(located_start, len(text)) if located_start is '' or located_end is '': return False self.select_editor_location(located_start, located_end) # Start position is moved after current found location. self.editor.mark_set(tk.INSERT, located_end) return True def search_backward(self, text): located_start = self.editor.search(text, tk.INSERT, stopindex='1.0', backwards=True, nocase=True) located_end = '{}+{}c'.format(located_start, len(text)) if located_start is '' or located_end is '': return False self.select_editor_location(located_start, located_end) # Start position is moved after current found location. self.editor.mark_set(tk.INSERT, located_start) return True def replace_selected_text(self, new_text): self.editor.delete('sel.first', 'sel.last') self.editor.insert('insert', new_text) def select_editor_location(self, selection_start, selection_end): print('Found location start: ', selection_start) print('Found location end: ', selection_end) selection_start_float = float(selection_start) self.editor.tag_remove(tk.SEL, "1.0", 'end') self.editor.tag_add(tk.SEL, selection_start, selection_end) self.editor.focus_force() self.editor.see(selection_start_float) def is_dirty(self): return self.editor.edit_modified() def rClicker(self, e): ''' right click context menu for all Tk Entry and Text widgets ''' try: def rClick_Copy(e, apnd=0): e.widget.event_generate('<Control-c>') def rClick_Cut(e): e.widget.event_generate('<Control-x>') def rClick_Paste(e): e.widget.event_generate('<Control-v>') def rClick_Highlight_Keyword(e): self.highlight_syntax(True) e.widget.focus() nclst = [ (' Cut', lambda e=e: rClick_Cut(e)), (' Copy', lambda e=e: rClick_Copy(e)), (' Paste', lambda e=e: rClick_Paste(e)), (' Highlight Keyword', lambda e=e: rClick_Highlight_Keyword(e)), ] rmenu = tk.Menu(None, tearoff=0, takefocus=0) for (txt, cmd) in nclst: rmenu.add_command(label=txt, command=cmd) rmenu.tk_popup(e.x_root + 40, e.y_root + 10, entry="0") except tk.TclError: print ' - rClick menu, something wrong' pass return "break" def highlight_syntax(self, enable=True): syntax_file = Path(Path( self.file_io.file_name).suffix[1:]).with_suffix('.hs') hs_config_data = Configuration.get_hs_configuration(syntax_file) if hs_config_data is None: print('No syntax file ', syntax_file) return #print(hs_config_data) keywords = hs_config_data['keyword']['tags'] keyword_fgcolor = hs_config_data['keyword']['color'] constant_fgcolor = hs_config_data['constant']['color'] numbers = re.findall(r'\d{1,3}', self.file_io.file_data) self.editor.tag_config('tg_kw', foreground=keyword_fgcolor) self.editor.tag_config('tg_num', foreground=constant_fgcolor) #keywords = ['package', 'public', 'private', 'abstract', 'internal', 'new', 'static', 'final', 'long', 'extends', # 'class', 'import', 'null', 'for', 'if', 'return', 'int', 'char', 'float', 'double', 'implements'] for keyword in keywords: self.editor.mark_set(tk.INSERT, '1.0') while True: located_end = self.highlight_keyword(keyword + ' ', 'tg_kw') if located_end == 0: break self.editor.mark_set(tk.INSERT, located_end) self.editor.mark_set(tk.INSERT, '1.0') for each_number in numbers: located_end = self.highlight_keyword(each_number, 'tg_num') if located_end != 0: self.editor.mark_set(tk.INSERT, located_end) print("Syntax highlight executed.") def highlight_keyword(self, text, tag): located_start = self.editor.search(text, tk.INSERT, stopindex=tk.END, forwards=True, nocase=False) located_end = '{}+{}c'.format(located_start, len(text)) print(located_start, ',', located_end) print('keyword', text) if located_start is '' or located_end is '': return 0 self.editor.tag_add(tag, located_start, located_end) return located_end